How to find an overloaded method in Java?

荒凉一梦 提交于 2019-12-04 22:59:18

Alternatively you could use Bean Utils from Apache Commons:

public static Method getAccessibleMethod(
        Class clazz,
        String methodName,
        Class[] parameterTypes)

According documentation:

Return an accessible method (that is, one that can be invoked via reflection) with given name and parameters. If no such method can be found, return null. This is just a convenient wrapper for getAccessibleMethod(Method method).

Parameters: clazz - get method from this class methodName - get method with this name parameterTypes - with these parameters types

The implementation get the accessible method and goes up in the hierarchy until it founds a match to it.

Direct to the Invocation

In order to perform invocation directly as you asked, you could use this method from the same API:

public static Object invokeExactMethod(
        Object object,
        String methodName,
        Object[] args,
        Class[] parameterTypes)
        throws
        NoSuchMethodException,
        IllegalAccessException,
        InvocationTargetException

or even

public static Object invokeExactMethod(
        Object object,
        String methodName,
        Object[] args)
        throws
        NoSuchMethodException,
        IllegalAccessException,
        InvocationTargetException

that first locates the method using getAccessibleMethod and later on invokes it.

The MethodHandle is a new way to get a overloaded method using a signature (java 7):

Example:

static class A {
    public String get() {
        return "A";
    }
}

static class B extends A {
    public String get() {
        return "B";
    }
}

public static void main(String[] args) throws Throwable {

    MethodHandles.Lookup lookup = MethodHandles.lookup();
    MethodType mt = MethodType.methodType(String.class);
    MethodHandle mh = lookup.findVirtual(A.class, "get", mt);;

    System.out.println(mh.invoke(new B()));
}

Outputs:

B
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!