public interface TestServiceIface {
default String test(String str, int flag) {
return str;
}
}
这样的界面,如果实现了界面,并且有一个实例,我怎样才能调用默认方法?如果使用反射,该怎么办? 而我只有这个接口,没有Impl类,也没有Impl instance.how来调用默认方法?如何在界面使用反射中调用默认方法
public interface TestServiceIface {
default String test(String str, int flag) {
return str;
}
}
这样的界面,如果实现了界面,并且有一个实例,我怎样才能调用默认方法?如果使用反射,该怎么办? 而我只有这个接口,没有Impl类,也没有Impl instance.how来调用默认方法?如何在界面使用反射中调用默认方法
可以通过反射访问接口默认方法如下:
Class<TestServiceIface> type = TestServiceIface.class;
Method defaultMethod = type.getMethod("test", String.class, int.class);
String result = (String) defaultMethod.invoke(instance, "foo", 0);
然而,如果子类重写默认方法,则overrided方法将被调用,这意味着接口默认方法还支持多态性。
或通过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
您的实例的类使用反射,如'instance.getClass()。getMethod(“test”)'不起作用? –
你的努力是什么? –
您可以像调用其他方法一样调用该方法,除非被覆盖。如果该方法已被覆盖,则没有正式的方法来绕过覆盖方法,这也与其他方法一样。 – Holger