[英]How to use Class type Generic in a method
我有一个实现接口方法的方法。 它看起来像这样:
@Override
public Double calculate(Class<Float> score) {
if (score == null) {
return null;
}
Double beta0 = new Double(-7.7631);
Double beta1 = new Double(0.0737);
Double beta2 = new Double(0.9971);
Log log = new Log();
Exp exp = new Exp();
Double logit = beta0 + (beta1 * score) + (beta2 * log.value(new Double(score + 1)));
Double rod = exp.value(logit) / (1 + exp.value(logit));
return rod;
}
介面
public interface Calculator<T,S> {
public T calculate(Class<S> params);
}
我收到编译错误, the operator '*' is not defined for the argument type(s) Double, Class<Float>
。
我想我已经预料到了,但是真的不知道如何解决。 抱歉,这是一个简单的问题.....
您可能不希望使用Class<Float>
而只希望将Float
作为方法参数。
数学运算符不适用于Class
类型, Class
类型用于定义实际的类(例如,在反射中使用)。
另外,请注意对double
, float
和其包装器进行的操作:精度可能会丢失,从而导致意外的结果。
我建议至少在内部使用BigDecimal
。
注意
看来您@Override
正在使用您的方法,这可能意味着类设计存在更大的问题。 我建议检查父类,然后推断出calculate
方法为什么将Class
作为参数。
编辑
我将您的接口方法更改为:
public T calculate(S param);
您也可以考虑向上绑定通用类型以扩展Number
。
符合以下条件的东西:
public interface Calculator<T extends Number, S extends Number> {
public T calculate(S param);
}
...以及一个实现的匿名示例:
Calculator<Double, Float> calc = new Calculator<Double, Float>() {
public Double calculate(Float param) {
// TODO logic
return null;
};
};
你不能使用
Double logit = beta0 + (**beta1 * score**) + (beta2 * log.value(new Double(score + 1)));
因为未定义运算符“ *”,所以不能将这两种不同的类型相乘。 您可以改用float。
您必须从Double
类获得double
值。 喜欢:
Double beta0 = new Double(0.07);
double x = beta0.doubleValue();
或在所有代码中使用double
原始数据类型。
干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.