是否可以使用一个明确定义其类类型的构造函数来编写泛型类?
这是我的尝试:
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();
}
}