2

私は次のジェネリッククラスを持っています:

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

ただし、これを実現するために、ジェネリック クラスにコンストラクターを含めたいと思います。何か案は?

4

1 に答える 1

4

既存のコンストラクタに加えて、ファクトリ メソッドが役立つようです。

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

別のコンストラクターにすることはできません。クラスはジェネリックであるため、コンストラクターはジェネリック型を処理し、それらをVandDに割り当てる必要がvalueありdisplayます。このジェネリック クラスのコンストラクターで特定の型にすることはできません。

于 2013-04-12T18:02:06.490 に答える