Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java reflection to create eval() method

I have a question about reflection I am trying to have some kind of eval() method. So i can call for example:

eval("test('woohoo')");

Now I understand the there is no eval method in java but there is reflection. I made the following code:

String s = "test";
Class cl = Class.forName("Main");
Method method = cl.getMethod(s, String.class);
method.invoke(null, "woohoo");

This works perfectly (of course there is a try, catch block around this code). It runs the test method. However I want to call multiple methods who all have different parameters.

I don't know what parameters these are (so not only String.class). But how is this possible? how can I get the parameter types of a method ? I know of the following method:

Class[] parameterTypes = method.getParameterTypes();

But that will return the parameterTypes of the method I just selected! with the following statement:

Method method = cl.getMethod(s, String.class);

Any help would be appreciated !

like image 505
heldopslippers Avatar asked Apr 12 '10 10:04

heldopslippers


2 Answers

You will need to call Class.getMethods() and iterate through them looking for the correct function.

For (Method method : clazz.getMethods()) {
  if (method.getName().equals("...")) {
    ...
  }
}

The reason for this is that there can be multiple methods with the same name and different parameter types (ie the method name is overloaded).

getMethods() returns all the public methods in the class, including those from superclasses. An alternative is Class.getDeclaredMethods(), which returns all methods in that class only.

like image 103
cletus Avatar answered Sep 24 '22 11:09

cletus


You can loop over all methods of a class using:

cls.getMethods(); // gets all public methods (from the whole class hierarchy)

or

cls.getDeclaredMethods(); // get all methods declared by this class

.

for (Method method : cls.getMethods()) {
    // make your checks and calls here
}
like image 26
Bozho Avatar answered Sep 23 '22 11:09

Bozho