mardi 10 mars 2015

What is the cleanest way to use Java Reflection to invoke a method with an ActionEvent parameter?

Here is a very simplified example of what I am trying to accomplish. I am maintaining code that was written a long time ago by someone else and do not have the ability to change it.



import java.awt.event.ActionEvent;
import java.lang.reflect.Method;




public class Main {
public static void main(String[] args) throws Exception {

Class cls = Class.forName("Main");
Main obj = (Main) cls.newInstance();

Method m = cls.getDeclaredMethod("test", ActionEvent.class);

m.invoke(obj, null); <--- throws an IllegalArgumentException
}

public void test(ActionEvent x) {
System.out.println("Yeah");
}
}


The above code throws java.lang.IllegalArgumentException: wrong number of arguments. I know I could pass new ActionEvent(new Object(), 0, null) as a parameter, but I am not sure this is the best/cleanest way to accomplish this. Note, the method test doesn't actually use the ActionEvent parameter.






Aucun commentaire:

Enregistrer un commentaire