通常、サーバントクラスは、idltojava コンパイラにより生成される ImplBase クラスを継承しなければなりません。サーバントクラスにほかの Java クラスの機能を継承させたい場合、この制限が問題になります。プログラミング言語 Java ではスーパークラスは 1 つしか指定できませんが、idltojava コンパイラにより生成される ImplBase クラスがこの位置を占めてしまいます。
このプログラム例 4 では、サーバントクラスに任意の Java クラスを継承させる方法を説明します。このプログラム例では、HelloServant クラスは、そのすべての実装を HelloBasic という Java クラスから継承しています。実行時、HelloServant に対するメソッド要求は、idltojava により生成された別のクラスに委譲されます。
プログラム例 4 は、実装の継承に関する拡張が行われている点を除いて、プログラム例 1 と同じです。このページでは、拡張部分のコードについてだけ説明します。
このページでは、次の内容について説明します。
HelloServant に対するメソッド要求をほかの Java クラスに委譲するサーバの実装
このプログラム例のコンパイル方法と実行方法については、「Hello World の構築方法と実行方法」を参照してください。
インタフェース定義 (
Hello.idl)
module HelloApp
{
interface Hello
{
string sayHello();
};
};
この IDL インタフェースは、次のコマンドでコンパイルします。
idltojava -ftie Hello.idl
これにより、HelloApp サブディレクトリに次の 2 つのファイルが生成されます。
HelloServer.java)// Copyright and License
import HelloApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
class HelloBasic
{
public String sayHello()
{
return "\nHello world !!\n";
}
}
class HelloServant extends HelloBasic implements _HelloOperations
{
}
public class HelloServer {
public static void main(String args[])
{
try{
// create and initialize the ORB
ORB orb = ORB.init(args, null);
// create servant and register it with the ORB
HelloServant servant = new HelloServant();
Hello helloRef = new _HelloTie(servant);
orb.connect(helloRef);
// get the root naming context
org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
NamingContext ncRef = NamingContextHelper.narrow(objRef);
// bind the Object Reference in Naming
NameComponent nc = new NameComponent("Hello", "");
NameComponent path[] = {nc};
ncRef.rebind(path, helloRef);
// wait for invocations from clients
java.lang.Object sync = new java.lang.Object();
synchronized (sync) {
sync.wait();
}
} catch (Exception e) {
System.err.println("ERROR: " + e);
e.printStackTrace(System.out);
}
}
}
HelloClient.java)// Copyright and License
import HelloApp.*;
import org.omg.CosNaming.*;
import org.omg.CORBA.*;
public class HelloClient
{
public static void main(String args[])
{
try{
// create and initialize the ORB
ORB orb = ORB.init(args, null);
// get the root naming context
org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");
NamingContext ncRef = NamingContextHelper.narrow(objRef);
// resolve the Object Reference in Naming
NameComponent nc = new NameComponent("Hello", "");
NameComponent path[] = {nc};
Hello helloRef = HelloHelper.narrow(ncRef.resolve(path));
// call the Hello server object and print results
String hello = helloRef.sayHello();
System.out.println(hello);
} catch (Exception e) {
System.out.println("ERROR : " + e) ;
e.printStackTrace(System.out);
}
}
}
idltojava -ftie Hello.idl
javac *.java HelloApp/*.java
tnameserv -ORBInitialPort 1050&
java HelloServer -ORBInitialPort 1050
java HelloClient -ORBInitialPort 1050
| ホーム |
Copyright © 1995-98 Sun Microsystems, Inc. All Rights Reserved.