我有一个问题,我无法弄清楚。 使用这些类:函数在Java中使用泛型重载
- PrimitiveToken
- GBVariable
- GBFloat:
public class GBFloat extends GBVariable<Float> {
public GBFloat(String name, Float value) { super(name, value); }
}
- PLUSTOKEN:
@Override
public GBVariable<?> eval() {
return sum(a.eval(),b.eval());
}
public static GBFloat sum(GBFloat a, GBFloat b) {
System.out.println("float added");
return new GBFloat("tmp", a.getValue()+b.getValue());
}
public static GBVariable<?> sum(GBVariable<?> a, GBVariable<?> b) {
throw new RuntimeException("Adding variables of types "+a.getClass().getSimpleName()+" and "+b.getClass().getSimpleName()+" is not supported.");
}
当我执行的PLUSTOKEN eval方法,而当a和b型GBFloat的Java仍然选择了sum(GBVariable<?> a, GBVariable<?> b)
方法并抛出异常:
Exception in thread "main" java.lang.RuntimeException: Adding variables of types GBFloat and GBFloat is not supported.
他不应该选择更具体方法?如果我先将a.eval()和b.eval()转换为GBVariables,它会正常工作。为什么是这样,我该如何优雅地解决这个问题?
a和b的声明这样:
过载new PrimitiveToken<GBFloat>(new GBFloat("tmp",Float.parseFloat("15.0")))
请将您的代码精简至**所需的最低**数量,以便将问题直接粘贴到您的问题中。 – 2012-03-12 17:09:44
你还没有显示变量'a'和'b'的声明,这是谜题中最关键的部分。如果它是'GBVariable > a = new GBFloat(...)',那么行为就像预期的那样。 – 2012-03-12 17:14:59