How to do call by reference in Java?

前端 未结 12 639
悲&欢浪女
悲&欢浪女 2021-01-30 17:36

Since Java doesnt support pointers, How is it possible to call a function by reference in Java like we do in C and C++??

相关标签:
12条回答
  • 2021-01-30 18:02

    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
    0 讨论(0)
  • 2021-01-30 18:03
    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
    
    0 讨论(0)
  • 2021-01-30 18:03

    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);
    
    0 讨论(0)
  • 2021-01-30 18:03

    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++.

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-01-30 18:06

    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.

    0 讨论(0)
提交回复
热议问题