Reputation: 796
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
Reputation: 8540
Call invoke()
method on the index you have got check this
Upvotes: 0
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