![](/img/trans.png)
[英]Is there any way with which I can avoid type casting while calling method with generic parameter?
[英]Is there any way to avoid casting this type?
考虑以下定义和实现Foo
接口的类:
public class MyClass {
public Foo getFoo() {
return new FooImpl();
}
public void fooMethod(Foo foo) {
final fooImpl = (FooImpl) foo;
fooImpl.hiddenMethod();
}
public interface Foo {
void doSomething();
}
private class FooImpl implements Foo {
public void doSomething();
void hiddenMethod() {
}
}
}
外部类将调用MyClass.getFoo()
以获取Foo
对象,并将其传递回fooMethod()
。 fooMethod()
预计FooImpl
的实施Foo
及管Foo
以FooImpl
所以它可以调用包私有方法hiddenMethod()
我的问题是,我对将Foo
为FooImpl
并不感到疯狂。 我可以用另一种模式来做同样的事情吗?
提前致谢...
这里的问题是您隐式地违反了封装原理。 您的类中有一个方法,该方法取决于实现,因此不属于Foo接口。 这是对OO负责人的侵犯,这只是冰山一角。 如果要设计一个新的Foo实现类,该类没有要调用的方法怎么办?
您应该重新设计代码,以便可以从Foo界面仅实现此调用方法。
您可以向Foo
接口添加hiddenMethod
方法
public interface Foo {
...
void hiddenMethod();
}
由于接口是支持的操作的约定,因此您不需要(应该吗?)将对象强制转换为访问接口外部的方法
你必须垂头丧气。
用这种方式做
public void fooMethod(Foo foo) {
if(foo instanceof FooImpl){
final FooImpl fooImpl = (FooImpl) foo;
fooImpl.hiddenMethod();
}
}
如果没有显式的向下转换,则不能对超级类型进行向下转换。 在使用instanceof
运算符进行向下转换之前,请务必进行检查。
- 编辑 -
如果要避免投射,请再做一件事。 hiddenMethod()
在Foo
界面中添加hiddenMethod()
。
public interface Foo {
void doSomething();
void hiddenMethod();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.