Finding most specific overloaded method using MethodHandle

前端 未结 5 436
旧时难觅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:12

    You can use MethodFinder.findMethod() to achieve it.

    @Test
    public void test() throws Exception {
        Foo foo = new Foo();
    
        Object object = 3L;
        Method method = MethodFinder.findMethod(Foo.class, "foo", object.getClass());
        method.invoke(foo, object);
    }
    
    
    public static class Foo {
        public void foo(Integer integer) {
            System.out.println("integer");
        }
    
        public void foo(Number number) {
            System.out.println("number");
        }
    
        public void foo(Object object) {
            System.out.println("object");
        }
    }
    

    Since it is in java root library, it is following JLS 15.12.

提交回复
热议问题