4 回答

TA贡献1874条经验 获得超12个赞
你的逻辑只匹配了方法名称并没有匹配参数类型吧。
public Object invoke(Object bean)throws Exception {
Method[] methods = clazz.getMethods();
for (Method method:methods) {
if(method.getName().equals(method.getName())){
return method.invoke(bean, param);
}
}
throw new Exception("找不到方法");
}
上面的代码是楼主查询的method的方式吧,我说未匹配类型,是指楼主自己写的代码中没有匹配参数的类型。而jdk内部是有这个判断的。
public class Test {
public String hello(int i) {
return "Hello" + i;
}
public static void main(String[] args) {
Test t = new Test();
try {
Method m = Test.class.getMethod("hello", Integer.class);
System.out.println(m.invoke(t, 9));
} catch (Exception e) {
e.printStackTrace();
}
try {
Method m = Test.class.getMethod("hello", int.class);
System.out.println(m.invoke(t, 8));
} catch (Exception e) {
e.printStackTrace();
}
}
}
我不太清楚楼主的代码是如何编写的,不过这段代码楼主可以运行一下看看区别。

TA贡献2036条经验 获得超8个赞
public static void main(String[] args) throws InvocationTargetException {
try {
Class<?> c = Class.forName("java.lang.StringBuilder");
Object instance = c.newInstance();
Method m = c.getMethod("append", String.class);
Object o = m.invoke(instance, "Hello World");
System.out.println(o);
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
}
我也是jdk1.8.0_101, 完全没问题啊

TA贡献1827条经验 获得超4个赞
The parameterTypes parameter is an array of Class objects that identify the method's formal parameter types, in declared order. If parameterTypes is null, it is treated as if it were an empty array.
api里面说了,如果第二个参数不传,会默认空数组,也就是找入参为空的方法,那肯定会报‘找不到方法’的错了
添加回答
举报