簡體   English   中英

Java錯誤:方法getMethod(String,Class <boolean> )對於類型Class未定義

[英]Java Error: The method getMethod(String, Class<boolean>) is undefined for type Class

我試圖將方法作為參數傳遞給另一個類中的方法。 該方法在第一類中定義,而另一類的方法是靜態的。 看到它會更容易理解:

設定

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

編譯時錯誤表明,您正在使用Java 1.4來編譯該類。 現在,在Java 1.4中,將數組參數定義為Type...是非法的,您必須將它們定義為Type[] ,這是為Class定義getMethod的方法:

Method getMethod(String name, Class[] parameterTypes)

因此,您不能使用簡化的1.5語法編寫:

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

您需要做的是:

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

更新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();
    }
});

您應該做的是創建一個接受MethodClickHander構造函數,如下所示

public ClickHandler(Method method) {

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

}

然后,在MyClass構造函數中按如下方式調用它:

public MyClass() {
    super(new ClickHandler(MyClass.class.getMethod("myMethod",boolean.class)));
}

原始答案

更詳細的說,來自Class#getMethod(String, Class...)的JavaDoc

返回一個Method對象,該對象反映此Class對象表示的類或接口的指定公共成員方法。

您的方法是private ,而不是public

如果要訪問私有方法,則應該使用Class#getDeclaredMethod(String, Class...)並通過調用setAccessible(true)使其可訪問。

問題是您的代碼無法編譯

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。

您遇到的另一個問題是,此方法需要一個實例,您似乎沒有要存儲該實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM