简体   繁体   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;
    }
}

Retrieving method: 检索方法:

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

Output: 输出:

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

But name of method is exactly the same! 但是方法的名称是完全一样的! Why I receive NoSuchMethodException ? 为什么我收到NoSuchMethodException? thanks. 谢谢。

After you fixed the misspelling, you are still looking for the wrong method: 解决拼写错误后,您仍然在寻找错误的方法:

The method is defined as: 该方法定义为:

getCompositeMessage(Type... strings)

but you are looking for 但是你在找

getCompositeMessage()

without parameters. 没有参数。

You need to use: 您需要使用:

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

The next problem will be the call to invoke(), you are passing the class references in stead of the object on which the method should be called. 下一个问题将是对invoke()的调用,您传递了类引用,而不是应在其上调用方法的对象。

The next bug is that you are not passing the correct arguments to the function: 下一个错误是您没有将正确的参数传递给该函数:

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

And the next problem is that you want output the result of the method instead of the method-object in the following line: 下一个问题是您要在以下行中输出方法的结果,而不是方法对象:

System.out.println(o);

You can find it using 您可以使用找到它

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

(that would be true if Type were a class or interface, since it's a generic parameter you are looking for this:) (如果Type是类或接口,那将是正确的,因为它是您要查找的通用参数:)

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

And the error you are getting results from the fact that the first parameter needs to be an instance, not the class Object. 而且您得到的错误是由于第一个参数需要是一个实例而不是对象Object的事实而导致的。

wrong: 错误:

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

right: 对:

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