Is it possible to write generic class with one constructor which explicitly defines type of its class?
Here is my attempt to do that:
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();
}
}
Your current code can easily lead to invalid states (e.g.
ComponentWrapper<SomeComponentThatIsNotAJLabel>that wraps aJLabel), and that’s likely why the compiler stops you there. You should use a static method instead in this case:Which would be much safer in many ways.