4 回答

TA貢獻(xiàn)1874條經(jīng)驗(yàn) 獲得超12個(gè)贊
你的邏輯只匹配了方法名稱并沒(méi)有匹配參數(shù)類型吧。
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的方式吧,我說(shuō)未匹配類型,是指樓主自己寫(xiě)的代碼中沒(méi)有匹配參數(shù)的類型。而jdk內(nèi)部是有這個(gè)判斷的。
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();
}
}
}
我不太清楚樓主的代碼是如何編寫(xiě)的,不過(guò)這段代碼樓主可以運(yùn)行一下看看區(qū)別。

TA貢獻(xiàn)2036條經(jīng)驗(yàn) 獲得超8個(gè)贊
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, 完全沒(méi)問(wèn)題啊

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超4個(gè)贊
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里面說(shuō)了,如果第二個(gè)參數(shù)不傳,會(huì)默認(rèn)空數(shù)組,也就是找入?yún)榭盏姆椒?,那肯定?huì)報(bào)‘找不到方法’的錯(cuò)了
添加回答
舉報(bào)