java RMI:作为方法调用的结果对列表执行的操作无效
我创建了一个简单的示例来试验Java的RMI特性。非常好。但是当我调用一个返回一个LinkedList对象的远程方法并向列表中添加一个元素时:什么都没有发生——元素没有被添加。见下面我的代码:
服务器上的接口和实现(远程对象):
public interface FooBar extends Remote {
List<Object> getList() throws RemoteException;
}
public class FooBarImpl extends UnicastRemoteObject implements FooBar {
private static final long serialVersionUID = -200889592677165250L;
private List<Object> list = new LinkedList<Object>();
protected CompanyImpl() throws RemoteException { }
public List<Object> getList() { return list; }
}
绑定它的代码(服务器):
Naming.rebind("//" + hostname + "/foobar", new FooBarImpl());
客户端代码:
FooBar foo = (FooBar) Naming.lookup("//" + hostname + "/foobar");
foo.getList().add(new String("Bar"));
System.out.println(foo.getList().size());
输出将是0
,而不是1
。因此,我的简单问题是:如何在不使用add
方法的情况下修复它(因为在服务器端使用add
方法可以工作)
编辑1: 这段代码运行得很好:
public class FooBarTest {
static class FooBarImpl {
public List<Object> list = new LinkedList<Object>();
public List<Object> getList() { return list; };
}
public static void main(String[] args) {
FooBarImpl test = new FooBarImpl();
test.getList().add(new String("Foo"));
System.out.println(test.getList().size()); // = 1
}
}
编辑2:此代码也可以使用(但我正在尝试从编辑1中复制简单代码):
@Override
public void add(Object o) throws RemoteException {
list.add(o);
}
FooBar foo = (FooBar) Naming.lookup("//" + hostname + "/foobar");
foo.add(new String("Bar"));
System.out.println(foo.getList().size()); // == 1
# 1 楼答案
这是因为,您正在将元素
Bar
添加到通过foo.getList()
获得的匿名List
对象,但您正在打印通过foo.getList()
再次获得的新List
对象的大小,该对象在以下行中为空:您应该使用以下代码: