use*_*818 0 java reflection methods types class
public class Test1<Type>
{
public Type getCompositeMessage(Type... strings)
{
Type val = (Type) "";
for (Type str : strings) {
val = (Type) ((String)val + (String)str);
}
return val;
}
}
Run Code Online (Sandbox Code Playgroud)
检索方法:
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();
}
Run Code Online (Sandbox Code Playgroud)
输出:
getCompositeMessage
java.lang.NoSuchMethodException: test1.Test1.getCompositeMessage()
at java.lang.Class.getMethod(Unknown Source)
at test1.Main.main(Main.java:25)
Run Code Online (Sandbox Code Playgroud)
但方法的名称完全一样!为什么我收到NoSuchMethodException?谢谢.
修复拼写错误后,您仍在寻找错误的方法:
该方法定义为:
getCompositeMessage(Type... strings)
Run Code Online (Sandbox Code Playgroud)
但你在找
getCompositeMessage()
Run Code Online (Sandbox Code Playgroud)
没有参数.
你需要使用:
c.getMethod("getCompositeMessage", Object[].class);
Run Code Online (Sandbox Code Playgroud)
下一个问题是调用invoke(),你传递类引用而不是应该调用该方法的对象.
下一个错误是您没有将正确的参数传递给函数:
Object o = m.invoke(new Test1<String>(), new Object[] {
new String[] {"777777777777777777777777"}});
Run Code Online (Sandbox Code Playgroud)
接下来的问题是您希望输出方法的结果而不是以下行中的方法对象:
System.out.println(o);
Run Code Online (Sandbox Code Playgroud)