jocopa3
jocopa3

Reputation: 796

How do I execute a method of a class using an array of methods in the class?

What I'm trying to do is execute a method in a class without knowing the method name. I have an array of methods from the class, and an index in of what method it is in the array, but not the actual method. This is what I attempted...but I don't know how to actually do it.

Class blocks = Blocks.class;
Method[] methods = blocks.getDeclaredMethods();
Blocks block = new Blocks();
String a = block.(methods[blockBox.getSelectedIndex()]);

Is there anyway to do it? I also can't rewrite my code to better suit this one situation.

Upvotes: 0

Views: 51

Answers (2)

Balaswamy Vaddeman
Balaswamy Vaddeman

Reputation: 8540

Call invoke() method on the index you have got check this

Upvotes: 0

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299108

For instance methods:

String a = (String) methods[blockBox.getSelectedIndex()].invoke(block);

For static methods:

String a = (String) methods[blockBox.getSelectedIndex()].invoke(null);

Provided that the methods have return type String and no parameters

Upvotes: 1

Related Questions