我想知道是否可以设置一个参数类型,它是实现给定接口的类的类型。看到一些代码,问题将变得更加清晰:
interface A {
A sum (???? another);
}
class AClass implements A {
private int internalStuff;
A public sum (???? another) {
// I want to access another.internalStuff in a type safe fashion
}
}
当然我可以替代????使用A类型,并在AClass.sum中,将其强制转换为AClass,但这很难看。可以" ????"用一些有意义的类型声明替换?
答案 0 :(得分:3)
Java中没有自我类型,所以你必须做一些小技巧来实现这一点。
您可以添加一个绑定到接口的递归类型的类型参数。实现类将此参数设置为自己的类型。像这样:
interface A<T extends A<T>> {
A sum (T another);
}
class AClass implements A<AClass> {
private int internalStuff;
public A sum(AClass another) {
// ....
}
}
尽管如此,AClass
并没有阻止implements A<SomeOtherAClass>
做什么。您必须信任实现类以提供正确的类型参数。