Access overloaded method via Reflection Api

user683224 :

How to distinguish a class overloaded method using Reflection e.g. :

method() and method(int arg)

void invoke(Object object, String methodName, int id) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
        object.getClass().getDeclaredMethod(methodName).invoke(object, int.class);
}

And call to this function :

getV(new Object(), "method", 33);

And it returns error java.lang.IllegalArgumentException: wrong number of arguments, That mean the method with no arguments is choosed by default. If i invoke the method without the int parameter it will work. I ask how to distinguish the overloaded method's ? I have read the docs for Class.getDeclaredMethod https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html Also there is an old post on SO but both sources aren't answering the same question How to find an overloaded method in Java?. Ofcourse Class.Object dosen't have method with name method i just used it for the example.

Holger :

You have to specify the parameter types to the lookup method, not the invoke method:

void invoke(Object object, String methodName, int id) throws ReflectiveOperationException {
    object.getClass().getDeclaredMethod(methodName, int.class).invoke(object, id);
}

But keep in mind that getClass() returns the actual class, which could be a subclass of the intended class, whereas getDeclaredMethod does not seach superclasses. getMethod does search superclasses, but only considers public methods.

To consider non-public methods within the type hierarchy, you would have to loop through the superclasses yourself when the method has not been found.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=358754&siteId=1