簡體   English   中英

為什么反射找不到方法?

[英]Why reflection doesn't find method?

public class Test1<Type>
{
    public Type getCompositeMessage(Type... strings)
    {
        Type val = (Type) "";

        for (Type str : strings) {
            val = (Type) ((String)val + (String)str);
        }
        return val;
    }
}

檢索方法:

try
{
    Class<?> c = Class.forName("test1.Test1");
    Method[] allMethods = c.getDeclaredMethods();
    for (Method m : allMethods) {
        String mname = m.getName();
        System.out.println(mname);
    }

    Method m = c.getMethod("getCompositeMessage");
    m.setAccessible(true);
    Object o = m.invoke(c, "777777777777777777777777");
    System.out.println(m);
}
catch (Exception e)
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}

輸出:

getCompositeMessage
java.lang.NoSuchMethodException: test1.Test1.getCompositeMessage()
at java.lang.Class.getMethod(Unknown Source)
at test1.Main.main(Main.java:25)

但是方法的名稱是完全一樣的! 為什么我收到NoSuchMethodException? 謝謝。

解決拼寫錯誤后,您仍然在尋找錯誤的方法:

該方法定義為:

getCompositeMessage(Type... strings)

但是你在找

getCompositeMessage()

沒有參數。

您需要使用:

c.getMethod("getCompositeMessage", Object[].class);

下一個問題將是對invoke()的調用,您傳遞了類引用,而不是應在其上調用方法的對象。

下一個錯誤是您沒有將正確的參數傳遞給該函數:

 Object o = m.invoke(new Test1<String>(), new Object[] {
          new String[] {"777777777777777777777777"}});

下一個問題是您要在以下行中輸出方法的結果,而不是方法對象:

System.out.println(o);

您可以使用找到它

Test1.class.getDeclaredMethod("getCompositeMessage", Type[].class);

(如果Type是類或接口,那將是正確的,因為它是您要查找的通用參數:)

Test1.class.getDeclaredMethod("getCompositeMessage", (Object) Object[].class);

而且您得到的錯誤是由於第一個參數需要是一個實例而不是對象Object的事實而導致的。

錯誤:

Object o = m.invoke(c /* c is a class Object, but it must be an instance */,
                    "777777777777777777777777" /* this must be an array */);

對:

Type1<String> t = new Type1<String>();
Object o = m.invoke(t, new Object[]{"foo", "bar"};

暫無
暫無

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

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