簡體   English   中英

泛型類的特定於類型的構造函數

[英]Type specific constructor for generic class

我有以下通用類:

public class DropdownItem<V, D> {

    private V value;
    private D display;

    public DropdownItem(V value, D display) {
        this.value = value;
        this.display = display;
    }

    public V getValue() {
        return value;
    }

    public void setValue(V value) {
        this.value = value;
    }

    public D getDisplay() {
        return display;
    }

    public void setDisplay(D display) {
        this.display = display;
    }
}

如何為特定類型創建構造函數?

例如,

public DropdownItem(CustomClass custom) {
    this(custom.getFoo(), custom.getBar());
}

要么

public DropdownItem(CustomClass custom) {
    this.value = custom.getFoo();
    this.display = custom.getBar();
}

這些解決方案均無效。 在實現泛型類時確實可以做到這一點:

DropdownItem<Integer, String> myItem = new DropdownItem<Integer, String>(custom.getFoo(), custom.getBar());

但是,我想在泛型類中包含一個構造函數來完成此操作。 有任何想法嗎?

看起來像工廠方法,除了現有的構造函數之外,還可以幫助您:

public static DropdownItem<Integer, String> getCustomClassInstance(CustomClass custom)
{
    return new DropdownItem<Integer, String>(custom.getFoo(), custom.getBar());
}

不能是其他構造函數。 您的類是通用的,因此任何構造函數都必須處理通用類型VD才能將它們分配給valuedisplay 它不能是此泛型類的構造函數中的特定類型。

暫無
暫無

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

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