Finding most specific overloaded method using MethodHandle

前端 未结 5 441
旧时难觅i
旧时难觅i 2020-12-14 01:50

Suppose I have three methods inside a given type (class/interface):

public void foo(Integer integer);
public void foo(Number number);
public void foo(Object          


        
5条回答
  •  忘掉有多难
    2020-12-14 02:27

    No, I haven't seen anything like that in MethodHandle API. Similar thing exists in commons-beanutils as MethodUtils#getMatchingAccessibleMethod so you don't have to implement that.

    It will look something like this:

    Object object = getLong();
    Method method = MethodUtils.getMatchingAccessibleMethod(this.getClass(), "foo", object.getClass());
    

    You can convert to MethodHandle API or just use the Method directly:

    MethodHandle handle = MethodHandles.lookup().unreflect(method);
    handle.invoke(this, object);
    

提交回复
热议问题