[英]Java reflection : how to call a method with private interface as argument?
[英]call variable argument method by reflection
public String testa(Object... args){
for (Object arg : args) {
System.out.println(arg);
}
return "a";
}
@Test
public void test28() throws InvocationTargetException, IllegalAccessException {
Method method = ReflectionUtil.getMethodByName(NormalTest.class, "testa");
//wrong number of arguments
// method.invoke(this);
//argument type mismatch
// method.invoke(this, 123);
//argument type mismatch
// method.invoke(this, new Object[]{123});
// argument type mismatch
// method.invoke(this, new Object[]{new int[]{123}});
//right
method.invoke(this, new Object[]{new Integer[]{123}});
}
NormalTest
類有一個testa
方法,使用反射來獲取這個方法並調用它,在上面5種方式中,只有最后一次成功,為什么需要用嵌套數組傳遞變量參數?
jdk版本是7。
public String testa(Object... args)
是語法糖
public String testa(Object[] args)
所以這是一個期待Object數組的方法。
Method.invoke()
期望包含要傳遞給方法的所有參數的對象數組。 因此,如果方法采用String和Integer,則必須傳遞包含String和Integer的Object []。 由於您的方法采用Object []作為參數,因此必須將包含Object []的Object []傳遞給Method.invoke()。 這就是你在最后一次嘗試中所做的事情。 但不是你在其他所有嘗試中所做的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.