是否可以编写一个具有一个构造函数的通用类,该构造函数明确定义了其类的类型?
这是我的尝试:
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();
}
}
JLabel label = new ComponentWrapper("text").getComponent()
。 - Michal Viciannew ComponentWrapper<JButton>("SomeString");
会怎么样呢?最好的情况是到处都会出现ClassCastException
... - Romainnew ComponentWrapper<JButton>("SomeString")
可能会导致编译错误。在运行时不会出现ClassCastException
。 - Michal Vician