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