具有显式类型构造函数的泛型类

Mic*_*ian 4 java generics

是否可以使用一个明确定义其类的类型的构造函数编写泛型类?

这是我尝试这样做的:

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();
    }

}
Run Code Online (Sandbox Code Playgroud)

Fra*_*eth 5

你可以施展它:

public ComponentWrapper(String title) {
    this((T) new JLabel(title));
}
Run Code Online (Sandbox Code Playgroud)

这是由于通用信息,不能用于某些情况.例如:

new ComponentWrapper() // has 2 constructors (one with String and one with Object since Generics are not definied).
Run Code Online (Sandbox Code Playgroud)

类本身无法预测此类使用,在这种情况下,最坏的情况(没有通用信息)被考虑.