クラスの型を明示的に定義する1つのコンストラクターでジェネリッククラスを作成することは可能ですか?
これが私の試みです:
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();
}
}