lundi 9 novembre 2020

How to use Reflection Invoke a method which contain null in varargs

I'm in the situation like a class contains the same method name, and we are trying to use reflection to call, but it's seemed to have an issue when one of the argument contains null

For example :


package test;

public class Invoker {
    public void test(String a, Integer b) {
        System.out.println("String, Integer");
    }

    public void test(Integer a, Integer b) {
        System.out.println("Integer, Integer");
    }

    public void invoke(String methodName, Object ...args) {
        try {
           Class<?>[] clazz = new Class[args.length];
            int i=0;
           for(Object a:args) {
               clazz[i++] = a != null ? a.getClass() : null;
           }

           Method m = this.getClass().getMethod(methodName, clazz);

           // ... Continue for invocation

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String ...args) {
        Invoker invoker = new Invoker();

        // happened to be null sometimes
        String a = null;
        Integer b = 123;

        System.out.println("Trigger Normally");
        invoker.test(a, b);

        System.out.println("Trigger via Reflection");
        invoker.invoke("test", a, b);
    }
}

Result

Trigger Normally
String, Integer
Trigger via Reflection
java.lang.NoSuchMethodException: test.Invoker.test(null, java.lang.Integer)
    at java.lang.Class.getMethod(Class.java:1678)
    at test.Invoker.invoke(Invoker.java:21)
    at test.Invoker.main(Invoker.java:42)

The Argument sometimes happened to be null, but if it is null, It will trigger NoSuchMethodException

Our method name not intended to be unique, it has to be overload structure.





Aucun commentaire:

Enregistrer un commentaire