I am trying to pass a method in as a parameter to a method in another class. The method is defined in the first class and the other class’s method is static. Seeing it will make it easier to understand:
Setup
public class MyClass extends ParentClass {
public MyClass() {
super(new ClickHandler() {
public void onClick(ClickEvent event) {
try {
OtherClass.responseMethod(MyClass.class.getMethod("myMethod",Boolean.class));
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void myMethod(Boolean success) {
if(success.booleanValue()) {
//do stuff
}
}
}
When I try to build, though, I get the following error:
Error
The method getMethod(String, Class<boolean>) is undefined for the type Class<MyClass>
The problem isn’t that it’s not finding myMethod, it’s not finding Class<MyClass>.getMethod and I don’t know why.
Update
We’ve reworked this part of the code and are not using ‘getMethodorgetDeclaredMethod`. Since npe found a couple of problems with what I was doing plus put a lot of effort into finding the answer, I’m accepting that answer.
Update 2
The compile-time error suggests, that you are using Java 1.4 to compile the class.
Now, in Java 1.4, it was illegal to define array parameters as
Type..., you had to define them asType[], and this is the way thegetMethodis defined for theClass:Because of that, you cannot use the simplified 1.5 syntax and write:
what you need to do is:
Update 1
The code you posted, does not compile because of another reason:
What you should do is create a
ClickHanderconstructor that accepts aMethod, like thisand then, in
MyClassconstructor invoke it like this:Original answer
More to this, from the JavaDoc of
Class#getMethod(String, Class...)And your method is
private, notpublic.If you want to get access to private methods, you should rather use
Class#getDeclaredMethod(String, Class...)and make it accessible by callingsetAccessible(true).