java泛型有助于强制不带参数的方法返回扩展A的对象并实现B?
这就是我目前的情况:
public abstract class UI {
public abstract MainPage getMainPage();
public void refresh() {
MainPage mainPage = getMainPage();
if ( ! (mainPage instanceof AbstractLayout)) {
throw new ClassCastException("Please subclass AbstractLayout");
}
// do stuff with mainPage
}
}
public class MyUI extends UI {
@Override
public MainPage getMainPage() {
return new MyPage(); // wrong: does not subclass AbstractLayout
}
}
public class MyPage implements MainPage {}
public class AbstractLayout {}
public interface MainPage {}
我希望删除getMainPage()以某种方式强制其覆盖返回AbstractLayout的实例。就像现在一样,我在运行时检查这个,但我想做这个编译时间。可以吗?
答案 0 :(得分:1)
是的,你可以使用泛型来强制getMainPage的返回类型来扩展AbstractLayout并实现MainPage而不需要AbstractLayout实现MainPage。一种解决方案是使UI通用。
这将导致编译器错误:
public abstract class UI<T extends AbstractLayout & MainPage> {
public abstract T getMainPage();
}
public class MyUI extends UI<MyPage> { // Compiler error: Bound mismatch
@Override
public MyPage getMainPage() {
return new MyPage();
}
}
public class MyPage implements MainPage {}
public class AbstractLayout {}
public interface MainPage {}
让MyPage扩展AbstractLayout将允许代码编译:
public class MyPage extends AbstractLayout implements MainPage {}