问题
Since Java doesnt support pointers, How is it possible to call a function by reference in Java like we do in C and C++??
回答1:
Real pass-by-reference is impossible in Java. Java passes everything by value, including references. But you can simulate it with container Objects.
Use any of these as a method parameter:
- an array
- a Collection
- an AtomicXYZ class
And if you change its contents in a method, the changed contents will be available to the calling context.
Oops, you apparently mean calling a method by reference. This is also not possible in Java, as methods are no first-level citizens in Java. This may change in JDK 8, but for the time being, you will have to use interfaces to work around this limitation.
public interface Foo{
void doSomeThing();
}
public class SomeFoo implements Foo{
public void doSomeThing(){
System.out.println("foo");
}
}
public class OtherFoo implements Foo{
public void doSomeThing(){
System.out.println("bar");
}
}
Use Foo
in your code, so you can easily substitute SomeFoo
with OtherFoo
.
回答2:
How to do call by reference in Java?
You cannot do call by reference in Java. Period. Nothing even comes close. And passing a reference by value is NOT the same as call by reference.
(Real "call by reference" allows you to do this kind of thing:
void swap(ref int i, ref int j) { int tmp = *i; *i = *j; *j = tmp }
int a = 1;
int b = 2;
swap(a, b);
print("a is %s, b is %s\n", a, b); // -> "a = 2, b = 1"
You simply can't do that in Java.)
Since Java doesn't support pointers ...
While this is technically true, it would not be an impediment to what you are trying to do.
Java does support references, which are like pointers in the most important respects. The difference is that you can't treat references as memory addresses by doing arithmetic on them, converting them to and from integer types and so on. And you can't create a reference to a variable because the concept does not exist in Java or the JVM architecture.
How is it possible to call a function by reference in Java like we do in C and C++??
Important note: this is NOT "call by reference". It is "call by value" using a reference to a function.
Prior to Java 8, references to functions were not supported as values. So you could not pass them as arguments, and you cannot assign them to variables.
However, you can define a class with one instance method, and use an instance of the class instead of a function reference. Other Answers give examples of this approach.
From Java 8 onwards, method references are supported using ::
syntax. There are 4 kinds of method reference:
- Reference to a static method:
ContainingClass::staticMethodName
- Reference to an instance method of a particular object:
containingObject::instanceMethodName
- Reference to an instance method of an arbitrary object of a particular type:
ContainingType::methodName
- Reference to a constructor:
ClassName::new
回答3:
Usually in java this is solved by using interfaces:
Collections.sort(list, new Comparator() {
@Override
public int compareTo(Object o1, Object o2) {
/// code
}
});
回答4:
The best way is to use an interface which performs the action.
// Pass a Runnable which calls the task() method
executor.submit(new Runnable() {
public void run() {
task();
}
});
public void task() { }
You can use reflections to call any method
Method method = MyClass.class.getMethod("methodToCall", ParameterType.class);
result = method.invoke(object, args);
回答5:
In Java, except for primitives, passing Object to a method/function is always by reference. See Oli Charlesworth's answer for the example.
For primitive types, you can wrap it using array: For example:
public void foo(int[] in){
in[0] = 2;
}
int[] byRef = new int[1];
byRef[0] = 1;
foo(byRef);
// ==> byRef[0] == 2.
回答6:
package jgf;
public class TestJavaParams {
public static void main(String[] args) {
int[] counter1 = new int[1];
counter1[0] = 0;
System.out.println(counter1[0]);
doAdd1(counter1);
System.out.println(counter1[0]);
int counter2 = 0;
System.out.println(counter2);
doAdd2(counter2);
System.out.println(counter2);
}
public static void doAdd1(int[] counter1) {
counter1[0] += 1;
}
public static void doAdd2(int counter2) {
counter2 += 1;
}
}
Output would be:
0
1
0
0
回答7:
JAVA does allow internal reference using objects. When one write this assignment Obj o1 = new Obj(); Obj o2=o1; What does it do, that both o1 and o2 points to the same address. Manipulating any object's space, will reflect in the other's also.
So to do this, as mentioned above you can either use Array, Collections
回答8:
http://www.javaworld.com/javaqa/2000-05/03-qa-0526-pass.html
Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.
回答9:
Java allows only call by value. However, references to objects can be transferred to the called function using call by value. These references if used to manipulate the data of the object in the called function, this change will be visible in the calling function also. We can not do pointer arithmetic on the references as we do with pointers but references can point to the data of the object using period operator which functions as '*' operator in C/C++.
回答10:
From Java The Complete Reference by Herbert Shildt 9th edition: "When you pass an object to a method, the situation changes dramatically, because objects are passed by what is effectively call-by-reference. Keep in mind that when you create a variable of a class type, you are only creating a reference to an object. Thus, when you pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by theargument. This effectively means that objects act as if they are passed to methods by use of call-by-referen ce. Changes to the object inside the method do affect the object used as an argument."
package objectpassing;
public class PassObjectTest {
public static void main(String[] args) {
Obj1 o1 = new Obj1(9);
System.out.println(o1.getA());
o1.setA(3);
System.out.println(o1.getA());
System.out.println(sendObj1(o1).getA());
System.out.println(o1.getA());
}
public static Obj1 sendObj1(Obj1 o)
{
o.setA(2);
return o;
}
}
class Obj1
{
private int a;
Obj1(int num)
{
a=num;
}
void setA(int setnum)
{
a=setnum;
}
int getA()
{
return a;
}
}
OP: 9 3 2 2
FInal call to getA() shows original object field 'a' was changed in the call to method public static Obj1 sendObj1(Obj1 o).
回答11:
Yes, you can implement Call by Reference in another way by "Pass by Reference".
- You should pass the reference object of a class created.
- Then you can manipulate the object's data by member function (.), which will be reflected in original data.
In below code the original data --> x is manipulated by passing the reference object.
public class Method_Call {
static int x=50;
public void change(Method_Call obj) {
obj.x = 100;
}
public static void main(String[] args) {
Method_Call obj = new Method_Call();
System.out.println(x);
obj.change(obj);
System.out.println(x);
}
}
Output: 50 100
来源:https://stackoverflow.com/questions/6029012/how-to-do-call-by-reference-in-java