How to do call by reference in Java?

前端 未结 12 646
悲&欢浪女
悲&欢浪女 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条回答
  •  -上瘾入骨i
    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);
    

提交回复
热议问题