Generic class with explicitly typed constructor

Is it possible to write a common class with one constructor that explicitly determines the type of its class?

Here is my attempt to do this:

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(); } } 
+4
source share
2 answers

Your current code can easily lead to invalid states (e.g. ComponentWrapper<SomeComponentThatIsNotAJLabel> that wraps JLabel ), and probably why the compiler will stop you there. Instead, you should use the static method:

 public static ComponentWrapper<JLabel> wrapLabel(final String title) { return new ComponentWrapper<JLabel>(new JLabel(title)); } 

Which would be much safer in many ways.

+4
source

You can use it:

 public ComponentWrapper(String title) { this((T) new JLabel(title)); } 

This is due to general information that cannot be used for some instances. For instance:

 new ComponentWrapper() // has 2 constructors (one with String and one with Object since Generics are not definied). 

The class itself cannot predict such use, in which case the worst case is considered (without general information).

+5
source

All Articles