例えば、以下のようなクライアントを作成
package sample.rmi.client;
import java.lang.reflect.Method;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import sample.rmi.service.Registry;
public class RMIClient {
private static int availables = 3;
public static void main(String args[]) {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
if (args.length < 1) {
System.err.println("Usage: sample.rmi.client.RMIClient <targetNo.> <args>...");
System.exit(-1);
}
int num = 0;
try {
num = Integer.parseInt(args[0]);
} catch(Exception e) {
System.err.println("Usage: sample.rmi.client.RMIClient <targetNo.> <args>...");
System.err.println("\t"+args[0]+" is not number");
System.exit(-1);
}
if (num>availables) {
System.err.println("Usage: sample.rmi.client.RMIClient <targetNo.> <args>...");
System.err.println("\tAvailable targetNo. is less than "+availables);
System.exit(-1);
}
//!-- for DEBUG
String[] objList = null;
try {
objList = Naming.list("*");
} catch(Exception e) {
e.printStackTrace();
}
for (int i=0;i<objList.length;i++) {
System.err.println(i+"\t"+objList[i]);
}
//-! for DEBUG
String[] argg = new String[args.length-1];
if (argg.length!=0) {
for (int i=0;i<args.length-1;i++) {
argg[i] = args[i+1];
}
}
String targetClassName = "sample.rmi.client.Service"+num;
Class targetClass = null;
try {
targetClass = Class.forName(targetClassName);
} catch(Exception e) {
e.printStackTrace();
System.exit(-1);
}
Class[] a = new Class[2];
a[0] = Registry.class;
a[1] = argg.getClass();
Object service = null;
try {
service = targetClass.newInstance();
} catch(Exception e) {
e.printStackTrace();
System.exit(-1);
}
Method m = null;
try {
m = targetClass.getDeclaredMethod("doService", a);
} catch(Exception e) {
e.printStackTrace();
System.exit(-1);
}
Registry registryRef = null;
try {
System.out.println("Client : looking up Registry");
String url = new String("rmi://:1099/Registry");
registryRef = (Registry)Naming.lookup(url);
} catch (NotBoundException e) {
System.err.println("Client : not bound for the identifier");
} catch(RemoteException e) {
System.err.println("Client : registry could not be contacted");
e.printStackTrace();
} catch(Exception e) {
System.err.println("Client : "+e.getMessage());
e.printStackTrace();
}
Object[] o = new Object[2];
o[1] = argg;
o[0] = registryRef;
try {
m.invoke(service, o);
} catch(Exception e) {
e.printStackTrace();
}
}
}
package sample.rmi.client;
import sample.rmi.service.Registry;
public interface ClientService {
public abstract void doService(Registry regis, String args[]);
}