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

时间:2012-06-22 18:31:27

标签: java class methods compiler-errors 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
        }
    }
}

但是当我尝试构建时,我收到以下错误:

错误

The method getMethod(String, Class<boolean>) is undefined for the type Class<MyClass>

问题不在于它找不到myMethod,而是找不到Class<MyClass>.getMethod而且我不知道为什么。

更新

我们已经重写了这部分代码,并没有使用'getMethod or getDeclaredMethod`。由于npe发现了我正在做的事情的几个问题,加上我付出了很多努力来找到答案,我接受了这个答案。

2 个答案:

答案 0 :(得分:5)

更新2

编译时错误表明您正在使用Java 1.4编译该类。 现在,在Java 1.4中,将数组参数定义为Type...是非法的,您必须将它们定义为Type[],这就是为{{1}定义getMethod的方式。 }}:

Class

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

Method getMethod(String name, Class[] parameterTypes)

您需要做的是:

MyClass.class.getMethod("myMethod",boolean.class));

更新1

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

MyClass.class.getMethod("myMethod",new Class[] {boolean.class}));

你应该做的是创建一个接受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(); } }); 的{​​{1}}构造函数,就像这样

ClickHander

然后,在Method构造函数中调用它:

public ClickHandler(Method method) {

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

}

原始答案

更多内容来自Class#getMethod(String, Class...)

的JavaDoc
  

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

您的方法是MyClass,而不是public MyClass() { super(new ClickHandler(MyClass.class.getMethod("myMethod",boolean.class))); }

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

答案 1 :(得分:1)

问题是您的代码无法编译

new ClickHandler() {
   // not in a method !!
        try {
            OtherClass.responseMethod(MyClass.class.getMethod("myMethod",boolean.class));
        } catch (Exception e) {
            e.printStackTrace();
        }

我假设ClickHandler有一个你应该定义的方法,你需要将此代码移动到该方法。在任何情况下,您都不能将此代码放在方法或初始化程序块之外。


来自getMethod

  

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

您的方法为private,而不是public

你可以使用的是getDeclaredMethod。

您遇到的另一个问题是此方法需要一个您似乎不存储的实例。