为实现接口的类强制执行返回类型

I J*_*I J 12 java generics

如何在实现类中强制执行getFoo()方法,返回相同实现类的类型列表.

public interface Bar{
     ....
     List<? extends Bar> getFoo(); 
}
Run Code Online (Sandbox Code Playgroud)

现在,实现Bar的类返回实现Bar的任何类的对象.我想让它更严格,以便实现Bar的类在getFoo()中返回一个只有它类型的对象的List.

Dan*_*den 18

不幸的是,这不能由Java的类型系统强制执行.

不过,您可以通过以下方式获得相当接近:

public interface Bar<T extends Bar<T>> {
    List<T> getFoo();
}
Run Code Online (Sandbox Code Playgroud)

然后你的实现类可以像这样实现它:

public class SomeSpecificBar implements Bar<SomeSpecificBar> {
    // Compiler will enforce the type here
    @Override
    public List<SomeSpecificBar> getFoo() {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

但没有什么可以阻止另一个类这样做:

public class EvilBar implements Bar<SomeSpecificBar> {
    // The compiler's perfectly OK with this
    @Override
    public List<SomeSpecificBar> getFoo() {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)