Is it possible to store a method in java in a variable?

Possible duplicate:
Java - creating an array of methods

Is it possible to store a method in java in a variable? For example, do I have an array of methods? If so, how do I do this?

+5
source share
7 answers

In Java 6 and below, you will need to use reflection (see java.lang.reflect). Java 7 should have some new features in this regard (in particular, it handles a method ( JSR 292 ) and new “calls to dynamic” things). Java 8 (in some way, then) looks like lambda expressions (and yes, this link refers to the OpenJDK page, but they say that Oracle is on board ), which are not exactly the same, but related.

+5
source

, . , . , . , , , . .

+2

, . Method.

+1

, Method.

+1

, Method, invoke (..)

+1
+1

Yes, reflection is one way. But you can use the interface.

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

let's say you have a class

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

Now you can create a function such as:

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

Here you can have an array of interfaces that implement the methods.

+1
source

All Articles