Is it posible in java?
void aaa(){}
ArrayList<Method> list = new ArrayList<Method>();
list.add(aaa);
If it isn't, how i can realize collection of methods (functions).
I want to get some method by ID.
You can do something like:
interface VoidFunction {
void evaluate();
}
...
List<VoidFunction> list = new ArrayList<>();
VoidFunction aaa = new VoidFunction() {
@Override
public void evaluate() {
aaa();
}
}
list.add(aaa);
In Java 8 this should be much easier and nicer:
List<Consumer<Void>> list = new ArrayList<>();
Consumer<Void> aaa = () -> {...};
list.add(aaa);
(I believe I have the syntax right)
If you already have the aaa method defined as a regular method, you'll be able to do something like:
list.add(MyClass::aaa);
list.get(0).evaluate(). You can change the name to whatever you want by changing the method in the interface, but with the snippet above that will work.You need to use reflection to get the Method, e.g.
this.getClass().getMethod("aaa")
Alternatively, if you don't need to access methods defined on a class, you can use Callables.
ArrayList<Callable> list = new ArrayList<Callable>();
list.add(new Callable() {
public String call() {
return "asdf";
}
});
I believe you can do it, but you need to use reflection to get the methods from a class/object. Maybe this links helps: http://tutorials.jenkov.com/java-reflection/methods.html
The way you have done it does not work.
You can call following method of Class
public Method[] getMethods() throws SecurityException
Returns an array containing Method objects reflecting all the public member methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.
public Method[] getDeclaredMethods() throws SecurityException
Returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private methods, but excludes inherited methods.
Read more here
Cheers !!
Commandpattern and then reflection.