简体   繁体   English

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

[英]Generic class with explicitly typed constructor

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

}

You could cast it: 你可以施展它:

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

This is due to the Generic information, that could not be used for some instances. 这是由于通用信息,不能用于某些情况。 For example: 例如:

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 this case the worst case (no Generic info) is considered. 类本身无法预测此类使用,在这种情况下,最坏的情况(没有通用信息)被考虑。

Your current code can easily lead to invalid states (eg ComponentWrapper<SomeComponentThatIsNotAJLabel> that wraps a JLabel ), and that's likely why the compiler stops you there. 您当前的代码很容易导致无效状态(例如,包装JLabel ComponentWrapper<SomeComponentThatIsNotAJLabel> ),这可能是编译器阻止您的原因。 You should use a static method instead in this case: 在这种情况下,您应该使用静态方法:

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

Which would be much safer in many ways. 在许多方面哪个更安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM