Passing an object by reference in Java

Possible duplicate:
How to follow a link in Java

Is it possible to pass an object by reference in Java

Like in C #

public static void SomeMethod(ref Object obj) { ... } 
+10
source share
5 answers

No, this is not possible in Java.

In Java, all method arguments are passed by value. Note that non-primitive type variables that are object references are also passed by value: in this case, a reference is passed by value. Please note that passing a reference by value does not match passing by reference.

+25
source

All object variables are object references. When you pass an object to a method, you pass an object reference already. If you do not want the original object to be affected, you must first clone it.

+21
source

Not. Java is just bandwidth.

However, you should not demand such a thing. You can pass an object and change its fields - this will be reflected in the caller.

+3
source

You will need to create a reference class. Fortunately, there is one. Try a look at AtomicReference . Please note that it is intended for concurrency, so it may not be suitable.

Another idea is to pass an Object array with a length of one.

+2
source

Passing Arguments of Reference Data Type

Reference data parameters , such as objects, are also passed to methods at cost. This means that when the method returns, the passed reference still refers to the same as before. However, the values ​​of the object fields can be changed in the method, if they have access levels.

Source: Java Tutorial > Passing Information for a Method or Constructor

0
source

All Articles