我正在打字,我想知道如何在静态上下文中调用默认方法我有一个这样的代码段。
interface InterfaceWithDefaultMethod{
public default void saySomething(final int a,final int b){System.out.println(String.format("Parameters are %d %d",a,b));}
}
public class StaticsMethodIsNotOverriden2 implements InterfaceWithDefaultMethod {
public static void main(String[] args) {
final StaticsMethodIsNotOverriden2 clazz = new StaticsMethodIsNotOverriden2();
clazz.saySomething(13,20);//Overriden method call with 13 20
clazz.callDefaultSaySomethingFromInstance();//Parameters are 1 2
/*HOW CALL public default void saySomething(final int a,final int b) METHOD HERE....????*/
clazz.InterfaceWithDefaultMethod.super.saySomething(1, 2);/*no enclosing instance of type InterfaceWithDefaultMethod is in scope*/
}
@Override
public void saySomething(int a, int b) {
System.out.println(String.format("Overriden method call with %d %d",a,b));
}
//THIS IS WHAT A WANT TO DO BUT IN STATIC CONTEXT...
private void callDefaultSaySomethingFromInstance(){
InterfaceWithDefaultMethod.super.saySomething(1, 2); /*CALLING DEFAULT METHOD FROM INSTANCE CONTEXT*/
}
}
是否可以使用 StaticsMethodIsNotOverriden2 实例从静态上下文调用 InterfaceWithDefaultMethod->saySomething 方法的默认方法??
抱歉,如果问题很简单。
这是行不通的。
最佳答案
没有。 default
方法是一个实例方法,在这种情况下,动态绑定(bind)将启动。没有构造用于覆盖方法的客户端来强制调用 super -执行。这只能从子类中完成(正如您在 callDefaultSaySomethingFromInstance
中所做的那样)
您唯一的选择是在子类中公开一个不同的方法,并使该方法调用已实现接口(interface)的默认方法:
class StaticsMethodIsNotOverriden2 implements InterfaceWithDefaultMethod {
public static void main(String[] args) {
...
clazz.superSaySomething(1, 2);
}
//a different name/signature needed
public void superSaySomething(int a, int b) {
System.out.println(String.format("Forcing super method call with %d %d", a, b));
//the subclass calls default method
InterfaceWithDefaultMethod.super.saySomething(a, b);
}
@Override
public void saySomething(int a, int b) {
System.out.println(String.format("Overriden method call with %d %d", a, b));
}
...
}
关于Java>=8 在静态上下文中使用 instanceof 实例调用接口(interface)上的默认方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58572457/