开发者

In java can i store a method in a variable? [duplicate]

开发者 https://www.devze.com 2023-03-04 01:51 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Java - Creating an array of methods
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Java - Creating an array of methods

In java can i store a method in a variable? For example can i have an arr开发者_JS百科ay of methods? If so how would i do this?


In Java 6 and below, you'd need to use reflection (see the java.lang.reflect package). Java 7 is meant to have some new features in this regard (specifically method handles (JSR 292) and the new "invoke dynamic" stuff). Java 8 (some way off, then) looks set to have lambda expressions (and yes, that link is to an OpenJDK page, but they say Oracle's on board), which aren't quite the same thing, but are related.


I will recommend you to hold the output in a variable rather than calling the function again. Because the variable is going to be held in memory as long as it requires. After that automatic garbage collection will take care of that to free it up from the memory. But if you put method in variable that will eat up the memory for its activation record stack each time it gets called. So its good practice to store output in variable instead of method.


Yeah you can do that. You have the Method class.


It is possible if you use reflection and the Method data type.


You can use reflection to get Method object and then you can call invoke(..) on it


Look what, for example, returns Class#getDeclaredMethods().


Yea reflection is one way. But you can use an interface.

interface I {
    int add (int a, int b);
}

say you have a class

class B implements I {
   int add(int a, int b){
        return a + b;
   }
}

now you can create a function like:

doCalculate(I mehthodInterface) {
    \\some calculations
    \\u can also use any other functions defined in this interface
    methodInterface.add(2, 3);
}

Here you can have array of interfaces that are implementing the methods.

0

精彩评论

暂无评论...
验证码 换一张
取 消