问题描述
我有一个由接口定义的类
I have a class defined by an interface
public interface Test {
void testMethod();
}
Test test = new TestImpl();
public class TestImpl implements Test {
@Override
public void testMethod() {
//Nothing to do here
}
public void anotherMethod() {
//I am adding this method in the implementation only.
}
}
如何调用anotherMethod?
How can I call anotherMethod?
test.anotherMethod(); //Does not work.
我希望能够在实现中定义一些方法,因为在我的生产代码中,测试界面涵盖了相当广泛的类,并由多个类实现。我使用实现中定义的方法来设置单元测试中DI框架未涵盖的依赖项,因此方法从实现变为实现。
I want to be able to define a few methods in the implementation only because in my production code, the Test interface covers a pretty broad spectrum of classes and is implemented by multiple classes. I use methods defined in the implementation to set dependencies that aren't covered by the DI framework in my unit testing so the methods change from implementation to implementation.
推荐答案
问题在于以下几行:
Test test = new TestImpl();
这告诉编译器忘记新对象是TestImpl并将其视为普通的旧测试。如您所知,Test没有anotherMethod()。
This tells the compiler to forget that the new object is a TestImpl and treat it as a plain old Test. As you know, Test does not have anotherMethod().
您所做的是upcasting(将对象转换为更通用的类型)。正如另一张海报所说,你可以通过不上传来解决你的问题:
What you did is called "upcasting" (casting an object to a more general type). As another poster has said, you can fix your problem by not upcasting:
TestImpl test = new TestImpl();
如果你确定一个Test对象真的是一个TestImpl,你可以向下转发它(告诉编译器它是一个更具体的类型):
If you're sure that a Test object is really a TestImpl, you can downcast it (tell the compiler it is a more specific type):
Test test = new TestImpl();
:
((TestImpl) test).anotherMethod();
然而,这通常是一个坏主意,因为它可能导致ClassCastException。使用编译器,而不是反对它。
This is generally a bad idea, however, since it can cause ClassCastException. Work with the compiler, not against it.
这篇关于使用实现中声明的接口中未定义的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!