dimanche 9 décembre 2018

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 class has a testa method, use reflection to get this method and call it, in above 5 ways, only the last is successful, why need to pass variable arguments with nested array?

jdk version is 7.





Aucun commentaire:

Enregistrer un commentaire