gpt4 book ai didi

java - 泛型类的类型特定构造函数

转载 作者:行者123 更新时间:2023-11-30 07:17:36 25 4
gpt4 key购买 nike

我有以下通用类:

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。它不能是此泛型类的构造函数中的特定类型。

关于java - 泛型类的类型特定构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15977867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com