samedi 3 mars 2018

Get a method of class with parameter of primitive type using Reflection

I am trying to get a method of a class using reflection where argument of that method is sometimes a primitive type or any Object.

Example:

public class A {

public void display(short a){
    System.out.println(a);
    }

}

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.rexample.model.A;

public class ReflectionExample {

    public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        ReflectionExample example=new ReflectionExample();
        example.print();
    }

    public void print() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        String nameOfTheMethod="display";//Assume name of the method is display
        short v=10;//Assume primitive type is short
        Object value=v;
        Method method=A.class.getDeclaredMethod(nameOfTheMethod,value.getClass());
        method.invoke(new A(),value);
    }

}

And i am getting the error:

Exception in thread "main" java.lang.NoSuchMethodException: com.rexample.model.A.display(java.lang.Short)
    at java.lang.Class.getDeclaredMethod(Class.java:2130)
    at com.rexample.test.ReflectionExample.print(ReflectionExample.java:34)
    at com.rexample.test.ReflectionExample.main(ReflectionExample.java:27)

Above code is just a small example of a larger program that i am currently building where i cannot able to get method of parameter type short or any other primitive type.

I cannot able to directly use short.class or Short.TYPE in my code , Since i am trying to do in a more generic way.

Is there any way to solve my issue for parameter of primitive type and of any objects?





Aucun commentaire:

Enregistrer un commentaire