dimanche 23 décembre 2018

How to use reflection to invoke a method with primitive arguments?

I am trying to create a method invokeMethod(String methodName, Object...args) which invokes a method from a superclass on the current instance. I have tried the following implementation.

    public void invokeMethod(String methodName, Object...args) {
        //Array to hold the classes of the arguments
        Class<?>[] classes = new Class<?>[args.length]; 
        //Initialize each class in the array to the class of each argument 
        for(int i = 0; i < args.length; i++)
            classes[i] = args[i].getClass();
        try {
            //find the method
            Method m = this.getClass().getMethod(methodName, classes);
            //invoke the method
            m.invoke(this, args);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

The problem with this implementation is if I try to invoke a method with primitive parameters, I get a NoSuchMethodException because it is looking for a method with parameters whose type is the wrapper class equivalent.

For example, if I try to invoke a method with signature line(float, float, float, float) by trying invokeMethod("line", 50f, 50f, 50f, 50f), I get an exception similar to

java.lang.NoSuchMethodException: DynamicSketch.line(java.lang.Float, java.lang.Float, java.lang.Float, java.lang.Float)
at java.base/java.lang.Class.getMethod(Class.java:2109)
at DynamicSketch.invokeMethod(DynamicSketch.java:32)
at DynamicSketch.setup(DynamicSketch.java:19)
at processing.core.PApplet.handleDraw(PApplet.java:2412)
at processing.awt.PSurfaceAWT$12.callDraw(PSurfaceAWT.java:1557)
at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:316)

Is there anyway to make my invokeMethod method work with primitive arguments?





Aucun commentaire:

Enregistrer un commentaire