Reputation:
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.
Upvotes: 1
Views: 1080
Reputation: 129507
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);
Upvotes: 4
Reputation: 3709
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 !!
Upvotes: 0
Reputation: 30032
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";
}
});
Upvotes: 2
Reputation: 6915
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.
Upvotes: 0