3

对不起,如果我的问题没有任何意义。我会在这里尝试解释一下。假设我有一个这样的基本接口:

public interface SimpleInterface {
    public void function1(); 
}

扩展接口如下:

public interface ExtendedInterface extends SimpleInterface{
    public void function2();
}

可以说我有一个实现的类ExtendedInterface

public class Implementation implements ExtendedInterface {

    @Override
    public void function1() {
        System.out.println("function1");
    }

    @Override
    public void function2() {
        System.out.println("function2");
    }
}

现在,function2()当我得到一个用类SimpleInterface实例化的基接口 ()时,有什么方法可以调用,如下所示:Implementation

SimpleInterface simpleInterface = new Implementation();

我知道它违背了接口的目的,但它可以让我免于进行大量代码更改。

4

4 回答 4

4

基本上,您必须强制转换为ExtendedInterface

SimpleInterface simpleInterface = new Implementation();
ExtendedInterface extendedInterface = (ExtendedInterface) simpleInterface;
extendedInterface.function2();

当然,如果simpleInterface引用的对象实际上没有实现,则强制转换将失败ExtendedInterface。这样做的必要性绝对是一种代码味道 - 它可能是您可用的最佳选择,但至少值得考虑替代方案。

于 2018-07-31T16:53:02.243 回答
1

首先,您应该检查对象实例是否实际上是实现类的实现,因为这可能是多个类实现此接口的情况。

你可以这样做:

//Somewhere in the code 
SimpleInterface simpleInterface = new Implementation();

//Now with the variable you can check it as below
if(simpleInterface instanceof Implementation)
Implementation implemenation = (Implementation)simpleInterface;
implemenation.function2();
于 2018-07-31T16:53:35.903 回答
1

可调用的方法受左侧类型 ( SimpleInterface) 的限制,并且由于SimpleInterface没有方法function2()function2()因此无法在simpleInterface对象上调用。

为了做到这一点,强制转换(特别是downcast)如下:

ExtendedInterface extendedInterface = (ExtendedInterface) simpleInterface;
extendedInterface.function2();

或者,更简洁地说:

((ExtendedInterface) simpleInterface).function2()
于 2018-07-31T16:53:43.570 回答
0

正如其他人的演员所建议的那样,这是一种选择,但它不是完全证明。我们可以在这里使用反射

    Method[] methods = simpleInterface.getClass().getDeclaredMethods();
    for (Method method : methods) {
        if (method.getName().equals("function2"))

        try {
                method.invoke(simpleInterface);
            } catch (Exception e) {
                e.printStackTrace();
            }

    }

使用上面的代码将确保function2在具有此方法的对象的引用上调用该方法

于 2018-07-31T16:59:08.070 回答