簡體   English   中英

Java反射,getMethod()

[英]Java Reflection, getMethod()

我正在使用Java反射的基礎知識並觀察類方法的信息。 我需要獲得一個匹配getMethod()函數描述的規范的方法。 但是,當我這樣做時,我得到一個NoSuchMethodException,我希望你能告訴我為什么我的實現是不正確的。

static void methodInfo2(String className) throws ClassNotFoundException, 

NoSuchMethodException{

        Class cls = null;
        try{
            cls = Class.forName(className);
        } catch(ClassNotFoundException e){
            e.printStackTrace();
        }
        System.out.println("Cls:  "+cls);


        Method method1 = cls.getMethod("test", null);
        System.out.println("method1:  "+method1);


    }

EDIT1:當我打印出“Cls:”+ cls時,輸出為“Cls:class a8.myclass2”。 為什么它附加了類部分? (a8是正確的,所以不要擔心)/ EDIT1

這是我用來從我的main函數讀取類的函數,然后我想使用參數“test”和null得到getMethod(),其中“test”是方法的名稱,null表示該方法沒有參數。 我正在讀的課叫做myclass2,在這里:

package a8;

public class myclass2 {

    void test(){
        //"takes no parameters"
        //"returns bool"
        //"name starts with test"
        //return true;
    }

}

如您所見,該方法確實存在於類中。 如果你能指出我的錯誤,我會非常感激。

讓您的測試方法公開。 我相信Class.getMethod()僅限於公共方法。

如果沒有你發布確切的異常和你的輸出,很難說,但我懷疑這是因為類在兩個獨立的包中,並且由於方法的默認修飾符只是protected它失敗。

使用getDeclaredMethod()來獲取通常不可見的方法。

暫無
暫無

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

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