所以我有这个代码:
public class RemoteImpl extends UnicastRemoteObject implements TestRemote {
private static final long serialVersionUID = 1L;
private static int counter = 0;
private int localizedCounter = 0;
protected RemoteImpl() throws RemoteException {
super();
}
@Override
public int getMeGlobalCounter() throws RemoteException {
counter++;
return counter;
}
@Override
public int getMeLocalizedCounter() throws RemoteException {
localizedCounter++;
return localizedCounter;
}
}
对于我的客户,我正在尝试:
public class TestClient {
public static void main(String[] args) throws Exception {
Registry registry = LocateRegistry.getRegistry("localhost", Constant.RMI_PORT);
TestRemote remote = (TestRemote) registry.lookup(Constant.RMI_ID);
System.out.println("Global counter:" + remote.getMeGlobalCounter());
System.out.println("Localized counter:" + remote.getMeLocalizedCounter());
}
}
运行此代码两次后,我期望看到:
Global counter:3
Localized counter:1
但是我看到了
Localized counter:3
那么为什么每次调用此方法时本地化计数器都不会重置?我不是每次都会得到一个新对象吗?
最佳答案
Am I not getting a new object every time?
不,你不是。您将获得绑定(bind)到注册表中的相同实例。 RMI 不会随心所欲地创建远程对象。
关于Java RMI 对象静态而不是静态字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22309312/