我正在学习Java RMI,并且创建了一个非常简单的服务器来计算斐波那契数。服务器(FibonacciServer)创建一个负责计算序列的对象(Fibonacci),并且该对象实现接口(IFibonacci):
FibonacciServer.java:
package myrmifibonacciserver; import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.RemoteException; public class FibonacciServer { public static void main(String args[]){ try{ Fibonacci fib = new Fibonacci(); Naming.rebind("fibonacci", fib); System.out.println("Fibonacci Server ready."); }catch(RemoteException rex){ System.err.println("Exception in Fibonacci.main " + rex); } catch (MalformedURLException ex) { System.err.println("MalformedURLException " + ex); } } }
斐波那契
package myrmifibonacciserver; import java.math.BigInteger; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class Fibonacci extends UnicastRemoteObject implements IFibonacci{ private static final long serialVersionUID = -4300545841720809981L; public Fibonacci() throws RemoteException{ super(); } @Override public BigInteger getFibonacci(int n) throws RemoteException { return getFibonacci(new BigInteger(Long.toString(n))); } @Override public BigInteger getFibonacci(BigInteger n) throws RemoteException { System.out.println("Calculating teh " + n + "th Fibonacci number"); BigInteger zero = BigInteger.ZERO; BigInteger one = BigInteger.ONE; if(n.equals(zero) || n.equals(one)) return one; BigInteger current = one; BigInteger low = one; BigInteger high = one; BigInteger temp; while(current.compareTo(n) == -1){ temp = high; high = high.add(low); low = temp; current = current.add(one); } return high; } }
IFibonacci:
package myrmifibonacciserver; import java.math.BigInteger; import java.rmi.Remote; import java.rmi.RemoteException; public interface IFibonacci extends Remote{ public BigInteger getFibonacci(int n) throws RemoteException; public BigInteger getFibonacci(BigInteger n) throws RemoteException; }
如您所见,这是一个非常基本的示例。我正在使用命令在Linux上启动RMI注册表rmiregistry &,它启动没有问题。
rmiregistry &
但是,当我单击运行按钮(在Eclipse或Netbeans中)运行我的小项目时,出现错误:
Exception in Fibonacci.main java.rmi.ServerException: RemoteException occurred in server thread; nested exception is: java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is: java.lang.ClassNotFoundException: myrmifibonacciserver.IFibonacci
而且我不知道为什么!起初我以为是因为存根,但是由于我使用的是Java 1.7,所以它们是自动创建的。我究竟做错了什么 ?
找不到代码库。原因是,从JDK 7开始,java.rmi.server.useCodebaseOnly属性默认情况下为 true ,而在先前版本中,默认情况下为 false 。
当property为 false时, 它将使用服务器的代码库,但在 真实 情况下,它将忽略它。
http://docs.oracle.com/javase/7/docs/technotes/guides/rmi/enhancements-7.html
您的问题将在较低的JDK中解决。前JDK6
JDK6