我确实查看了建议的可能重复项。他们不问这个,而是问相关的事情。
我在 Java 8 中有这个所需的结构:
class BaseClass {
int method(int arg) {...} // does 99% of the work
}
interface MixinInterface { // intended only for subclasses of BaseClass
default int method(int arg) {
// what I want:
// effectively Subclass.super.method(arg)
int ret = this.super.method(arg);
{ do some embellishment on super.method results }
return(ret);
}
}
class Subclass
extends BaseClass
implements MixinInterface
{
}
是的,可以使用反射来做到这一点,或者向接口(interface)继承类添加一个 callSuperMethod() 方法,但它要么非常慢,要么很困惑。通过反射,找到继承接口(interface)的对象的父类(super class)(从而使其“super.method”被接口(interface)的默认值覆盖),从父类(super class)“class”获取方法句柄并调用它。
最佳答案
基本上,您不能在接口(interface)和基类中拥有相同的方法签名,但仍然可以独立使用两者,即使反射很棘手,您也需要求助于 MethodHandles
。
一个选项是删除扩展 BaseClass 并执行类似于装饰器模式的操作。
class BaseClass {
int method(int arg) {...} // does 99% of the work
}
interface MixinInterface { // intended only for subclasses of BaseClass
default int method(int arg) {
// what I want:
// effectively Subclass.super.method(arg)
int ret = getBaseClass().method(arg);
return(ret);
}
BaseClass getBaseClass();
}
class Subclass implements MixinInterface
{
private final BaseClass baseClass;
public Subclass(BaseClass baseClass) {
this.baseClass = baseClass;
}
@Override
public BaseClass getBaseClass() {
return baseClass;
}
// forward other method calls to baseClass (can be included in the MixinInterface as well)
}
另一个选项重命名装饰器方法并在BaseCase
中使用它,这样implements MixinInterface
几乎是多余的,应该用静态方法调用替换(特别是如果你只有一种装饰方法)。对于这个,装饰器链是不可能轻易实现的。
abstract class BaseClass {
abstract int methodDecorator(int originalReturn);
int method(int arg) {
// do 99% of the work
return methodDecorator(0);
}
}
interface MixinInterface {
default int methodDecorator(int arg) {
return arg;
}
}
class Subclass extends BaseClass implements MixinInterface {
@Override
public int methodDecorator(int originalReturn) {
// Sadly you need this forwarding, making this approach a bit clunky
return MixinInterface.super.methodDecorator(originalReturn);
}
}
关于java - 是否可以从接口(interface)调用被接口(interface) "default"覆盖的继承父类(super class)的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47087992/