[英]Generic class with explicitly typed constructor
是否可以使用一个明确定义其类的类型的构造函数编写泛型类?
这是我尝试这样做的:
import javax.swing.JComponent;
import javax.swing.JLabel;
public class ComponentWrapper<T extends JComponent> {
private T component;
public ComponentWrapper(String title) {
this(new JLabel(title)); // <-- compilation error
}
public ComponentWrapper(T component) {
this.component = component;
}
public T getComponent() {
return component;
}
public static void main(String[] args) {
JButton button = new ComponentWrapper<JButton>(new JButton()).getComponent();
// now I would like to getComponent without need to cast it to JLabel explicitly
JLabel label = new ComponentWrapper<JLabel>("title").getComponent();
}
}
你可以施展它:
public ComponentWrapper(String title) {
this((T) new JLabel(title));
}
这是由于通用信息,不能用于某些情况。 例如:
new ComponentWrapper() // has 2 constructors (one with String and one with Object since Generics are not definied).
类本身无法预测此类使用,在这种情况下,最坏的情况(没有通用信息)被考虑。
您当前的代码很容易导致无效状态(例如,包装JLabel
ComponentWrapper<SomeComponentThatIsNotAJLabel>
),这可能是编译器阻止您的原因。 在这种情况下,您应该使用静态方法:
public static ComponentWrapper<JLabel> wrapLabel(final String title) {
return new ComponentWrapper<JLabel>(new JLabel(title));
}
在许多方面哪个更安全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.