[英]Type specific constructor for generic class
I have the following 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;
}
}
How do I create a constructor for specific types? 如何为特定类型创建构造函数?
For example, 例如,
public DropdownItem(CustomClass custom) {
this(custom.getFoo(), custom.getBar());
}
or 要么
public DropdownItem(CustomClass custom) {
this.value = custom.getFoo();
this.display = custom.getBar();
}
Neither of those solutions work. 这些解决方案均无效。 It does work to do this when implementing the generic class:
在实现泛型类时确实可以做到这一点:
DropdownItem<Integer, String> myItem = new DropdownItem<Integer, String>(custom.getFoo(), custom.getBar());
However, I would like to include a constructor in the generic class to accomplish this. 但是,我想在泛型类中包含一个构造函数来完成此操作。 Any ideas?
有任何想法吗?
It looks like a factory method, in addition to the existing constructor, can help you: 看起来像工厂方法,除了现有的构造函数之外,还可以帮助您:
public static DropdownItem<Integer, String> getCustomClassInstance(CustomClass custom)
{
return new DropdownItem<Integer, String>(custom.getFoo(), custom.getBar());
}
It can't be another constructor. 不能是其他构造函数。 Your class is generic, so any constructor must deal with generic types
V
and D
to assign them to value
and display
. 您的类是通用的,因此任何构造函数都必须处理通用类型
V
和D
才能将它们分配给value
和display
。 it can't be specific types in the constructor(s) for this generic class. 它不能是此泛型类的构造函数中的特定类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.