簡體   English   中英

具有顯式類型構造函數的泛型類

[英]Generic class with explicitly typed constructor

是否可以使用一個明確定義其類的類型的構造函數編寫泛型類?

這是我嘗試這樣做的:

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

}

你可以施展它:

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

這是由於通用信息,不能用於某些情況。 例如:

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

類本身無法預測此類使用,在這種情況下,最壞的情況(沒有通用信息)被考慮。

您當前的代碼很容易導致無效狀態(例如,包裝JLabel ComponentWrapper<SomeComponentThatIsNotAJLabel> ),這可能是編譯器阻止您的原因。 在這種情況下,您應該使用靜態方法:

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

在許多方面哪個更安全。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM