Is there any way to
Java passes everything by value, and references are also passed that way. You can modify the object behind the reference, but you cannot modify the reference itself. I mean:
publicclass Test{
static Object obj =null;
publicstaticvoid a(Object o){
o =new Integer(5);
}
publicstaticvoid main(String[] args){
a(obj);
// the output will be null
System.out.println(obj);
}
}
I would like to know that is there any way to function "a" to modify the reference? Any tricky thing likejava.lang.ref or something like this?
In my real problem theobj is out of scope, so obj = new Int... is not a solution for me.
I also cannot change the signature's return value fromvoid toObject, because it predefined in a library that I use.
With some workaround I'm able to solve the situation, but the best would be that if I could change the reference behind "o".
Any tips?
[1557 byte] By [
roantea] at [2007-10-3 2:55:11]

No. This is absolutely impossible with java. I obviously don't know your exact situation, but if the method takes an Object, maybe you can pass in a 1-length array and change the 0'th element in the array. Otherwise if, as you say, your hands are tied as to the method's signature, you're hosed. :-) If you think about it, when you pass something into a method, you're not counting on that thing's reference being changed by the method. I think if something like that were available, it would cause really nasty bugs and allow developers to muck with code that's not in their scope in ways they really shouldn't. Can you imagine if you pass in an object to a method and the method sets the reference to null? Can you spell NPE?
Thanks, that was my thought, too. Anyway, it's not a world-shaking problem, I was just curios :-) Just got the idea because in C++ that's the default behaviour for references :-)
True. At least in C++ you have to use the & operator to pass the reference or you get a compile-time error. If you could change external references in java without the calling method having to specify it, it would allow the called method to hijack the caller's code to some extent. Also, since C++ passes copies of objects around (a statement like a=b calls an operation, not a simple reference copy), the & operator (or a pointer) is needed so that you don't have to unnecessarily clone everything all the time. Java doesn't have this particular problem/capability.