Java错误:未为类型Class定义方法getMethod(String,Class <boolean>)

ele*_*y19 2 java methods compiler-errors class undefined

我试图将方法作为参数传递给另一个类中的方法。该方法在第一类中定义,而另一类的方法是静态的。看到它会更容易理解:

设定

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试构建时,出现以下错误:

错误

The method getMethod(String, Class<boolean>) is undefined for the type Class<MyClass>
Run Code Online (Sandbox Code Playgroud)

问题不是没有找到myMethod,没有找到Class<MyClass>.getMethod,我也不知道为什么。

更新资料

我们已经重新编写了这部分代码,并且没有使用'getMethod orgetDeclaredMethod ' 。由于npe在我所做的事情中发现了两个问题,并且在寻找答案上付出了很多努力,因此我接受了这个答案。

npe*_*npe 5

更新2

编译时错误提示您正在使用Java 1.4来编译该类。现在,在Java 1.4中,它是非法的,以定义阵列参数Type...,你不得不对他们的定义Type[],这是方式getMethod是为定义Class

Method getMethod(String name, Class[] parameterTypes)
Run Code Online (Sandbox Code Playgroud)

因此,您不能使用简化的1.5语法编写:

MyClass.class.getMethod("myMethod",boolean.class));
Run Code Online (Sandbox Code Playgroud)

您需要做的是:

MyClass.class.getMethod("myMethod",new Class[] {boolean.class}));
Run Code Online (Sandbox Code Playgroud)

更新1

您发布的代码由于其他原因而无法编译:

super(new ClickHandler() {

    // This is anonymous class body 
    // You cannot place code directly here. Embed it in anonymous block, 
    // or a method.

    try {
        OtherClass.responseMethod(
            MyClass.class.getMethod("myMethod",boolean.class));
    } catch (Exception e) {
        e.printStackTrace();
    }
});
Run Code Online (Sandbox Code Playgroud)

您应该做的是创建一个ClickHander接受的构造函数Method,如下所示

public ClickHandler(Method method) {

    try {
        OtherClass.responseMethod(method);
    } catch (Exception e) {
        e.printStackTrace();
    }

}
Run Code Online (Sandbox Code Playgroud)

然后在MyClass构造函数中像这样调用它:

public MyClass() {
    super(new ClickHandler(MyClass.class.getMethod("myMethod",boolean.class)));
}
Run Code Online (Sandbox Code Playgroud)

原始答案

除此之外,来自JavaDoc的 Class#getMethod(String, Class...)

返回一个Method对象,该对象反映此Class对象表示的类或接口的指定公共成员方法。

而你的方法private不是public

如果您想访问私有方法,则应该使用Class#getDeclaredMethod(String, Class...)并通过调用使其可访问setAccessible(true)