当我使用类型参数创建一个类时:
public abstract class AbstractBox<T> {
abstract T getContent();
}
Run Code Online (Sandbox Code Playgroud)
那么我仍然可以创建一个没有类型参数的子类:
class SomeBox extends AbstractBox { // DISALLOW THIS
@Override
Something getContent() {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
我可以以某种方式强制子类提供类型参数(即使它只是Object)?例如,我想禁止上述内容但允许:
class SomeBox extends AbstractBox<Something> { // ALLOW THIS
@Override
Something getContent() {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:这不是重复的可以覆盖的方法在返回类型上有所不同?.该问题询问重写方法是否可以返回type参数的子类型.
我的问题是,我是否可以强制执行带有类型参数的抽象的任何子类必须提供类型参数.
如果你想检查AbstractBox扩展时是否提供了类型参数,你可以这样做:
abstract class AbstractBox<T> {
protected AbstractBox() {
// First, find the direct subclass of AbstractBox
Class<?> cls = getClass();
while(cls.getSuperclass() != AbstractBox.class)
cls = cls.getSuperclass();
// Then, check if it's superclass is parametrized
if (!(cls.getGenericSuperclass() instanceof ParameterizedType)) {
throw new RuntimeException("Must parametrize the extension of AbstractBox.");
}
}
abstract T getContent();
}
Run Code Online (Sandbox Code Playgroud)
首先需要获取直接子类,以便在直接子类AbstractBox使用参数扩展然后再次子类化的情况下不会中断。
请注意,这也将接受 的情况SomBox extends AbstractBox<String>。
| 归档时间: |
|
| 查看次数: |
94 次 |
| 最近记录: |