问题
In RMI, I can only get return value by
InetSocketAddress address = new InetSocketAddress(hostname, port);
Server server = Stub.create(Server.class, address);
int return = server.getValue();
But, I can't get it by
public class Return {
int value;
}
InetSocketAddress address = new InetSocketAddress(hostname, port);
Server server = Stub.create(Server.class, address);
Return return = new Return();
server.getValue(return);
I know arguments will be serialized and deserialized, but that's not my question, my question is "why can't Java emulate a pass-by-reference as a pass by in-out, as was done in C with RPC?", I think it's related to java environment. By in-out I mean in C with RPC, you can get return value by
int return;
rpc.getValue(&return);
Hope now my question is clear.
回答1:
Returning additional object proxies would pose an implementation challenge. As things stand, there's only one way to create a remote object. if methods are allowed to spawn more remote objects just by returning regular objects, then all those calls need to be intercepted, objects properly catalogued, etc.
In other words, the Java people - unlike , e. g. DCOM people - decided not to do the extra plumbing. And that will always be the answer to the "why is system A unlike system B" quesions.
回答2:
A reference is a memory address on your computer. With RMI, you are trying to pass that memory address to (potentially) another machine, where that memory address won't make sense in that context. The other machine will not now how to interpret that address. This is only why values can be passed.
回答3:
When you pass arguments to a method by "pass by reference" you are passing the reference, which is not possible in remote calls. And remember that Java only supports pass by values (even object references).
You may say the RMI runtime can deserialize all arguments back to the client, but this will be the problem:
Suppose you have a Long as an argument, so the java runtime will serialize it to server, then what? Shall it deserialize it? remember that Longs are immutable.
If Java runtime creates another instance of Long, then how can it update all instances referring to old Long (which was passed as an argument)?
来源:https://stackoverflow.com/questions/9486419/why-java-rmi-cant-get-return-value-by-reference