java是否可以用特定类型的值初始化泛型变量?
我有一个类,我想用String
或int
值实例化它,我将相应的实例变量value
定义为泛型类型T
:
public class MathValue<T extends Object> {
private boolean isOperand, isOperator;
// a generic-typed instance variable:
private T value;
// constructor:
public MathValue(int operand) {
// compile-error -- "Incompatible types: required T, found Integer"
this.value = new Integer(operand);
this.isOperand = true;
this.isOperator = false;
}
// constructor:
public MathValue(String operator) {
// compile-error -- "Incompatible types: required T, found String"
this.value = operand;
this.isOperand = false;
this.isOperator = true;
}
}
我可以使用一个单独的构造函数,使用类型为T
的形式参数,但我想用String
或int
参数强制类的实例化:
public class MathValue<T extends Object> {
private boolean isOperand, isOperator;
// a generic-typed instance variable:
private T value;
// it totally works, but does not enforce specific-typed instantiation:
public MathValue(T operandOrOperator) {
this.value = operandOrOperator;
if (operandOrOperator instanceof Integer) {
this.isOperand = true;
this.isOperator = false;
} else if (operandOrOperator instanceof String) {
this.isOperand = false;
this.isOperator = true;
}
}
}
因此,尽管存在逻辑错误,希望使泛型类型的类“不那么泛型”,但有可能用特定的类型化值实例化泛型变量吗?
# 1 楼答案
你可以创建工厂方法。现在它可能看起来是这样的:
如果你绝对需要一个构造函数(例如,你不知道你要提前创建的类型),那么我就无法绕过@RohitJain的建议