如何在界面使用反射中调用默认方法

时间:2017-07-25 10:52:41

标签: java-8

Microsoft.Owin.Security.Twitter
像这样的接口,如果实现了接口,并且有一个实例,我该如何调用default方法?如果用反射,该怎么办? 我只有这个接口,没有Impl类,没有Impl instance.how来调用默认方法?

2 个答案:

答案 0 :(得分:3)

您可以通过反射访问界面默认方法,如下所示:

Class<TestServiceIface> type = TestServiceIface.class;

Method defaultMethod = type.getMethod("test", String.class, int.class);

String result = (String) defaultMethod.invoke(instance, "foo", 0);

但是,如果子类覆盖默认方法,则将调用覆盖的方法,这意味着接口默认方法也支持多态

答案 1 :(得分:3)

或通过MethodHandle,但请注意您确实需要该接口的实现类:

static class Impl implements TestServiceIface {

}

用法:

    MethodType methodType = MethodType.methodType(String.class, String.class, int.class);
    MethodHandle handle = MethodHandles.lookup().findVirtual(TestServiceIface.class, "test", methodType);

    String result = (String) handle.invoke(new Impl(), "test", 12);
    System.out.println(result); // test