[英]How to use Class type Generic in a method
I have a method that implements an interface method. 我有一个实现接口方法的方法。 it looks like this:
它看起来像这样:
@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;
}
The interface 介面
public interface Calculator<T,S> {
public T calculate(Class<S> params);
}
I get a compile error that the operator '*' is not defined for the argument type(s) Double, Class<Float>
. 我收到编译错误,
the operator '*' is not defined for the argument type(s) Double, Class<Float>
。
I guess I expected this, but don't really know how to fix it. 我想我已经预料到了,但是真的不知道如何解决。 Apologies if this is a simple question.....
抱歉,这是一个简单的问题.....
You probably don't want a Class<Float>
but just a Float
as your method parameter. 您可能不希望使用
Class<Float>
而只希望将Float
作为方法参数。
Mathematical operators don't apply to the Class
type, which is used to define an actual class (eg used in reflection). 数学运算符不适用于
Class
类型, Class
类型用于定义实际的类(例如,在反射中使用)。
Also, careful with operations on double
s, float
s and their wrappers: the precision can be lost an yield unexpected results. 另外,请注意对
double
, float
和其包装器进行的操作:精度可能会丢失,从而导致意外的结果。
I advise to use BigDecimal
at least internally. 我建议至少在内部使用
BigDecimal
。
Note 注意
It seems you are @Override
ing your method, which likely implies a bigger issue with class design. 看来您
@Override
正在使用您的方法,这可能意味着类设计存在更大的问题。 I would advise to check on the parent class and infer why the calculate
method takes a Class
as parameter. 我建议检查父类,然后推断出
calculate
方法为什么将Class
作为参数。
Edit 编辑
I would change your interface method to: 我将您的接口方法更改为:
public T calculate(S param);
You could also consider binding your generic types upwards to extend Number
. 您也可以考虑向上绑定通用类型以扩展
Number
。
Something in the lines of: 符合以下条件的东西:
public interface Calculator<T extends Number, S extends Number> {
public T calculate(S param);
}
... and an anonymous example for implementation: ...以及一个实现的匿名示例:
Calculator<Double, Float> calc = new Calculator<Double, Float>() {
public Double calculate(Float param) {
// TODO logic
return null;
};
};
You can not use 你不能使用
Double logit = beta0 + (**beta1 * score**) + (beta2 * log.value(new Double(score + 1)));
because operatator "*" is not defined for it... You can not multiply these two different types. 因为未定义运算符“ *”,所以不能将这两种不同的类型相乘。 You can use float instead.
您可以改用float。
You have to get the double
value from Double
class. 您必须从
Double
类获得double
值。 Like: 喜欢:
Double beta0 = new Double(0.07);
double x = beta0.doubleValue();
Or use the double
primitive data type in all your code. 或在所有代码中使用
double
原始数据类型。
Cheers! 干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.