2012-03-12 23 views
0

我有一个问题,我无法弄清楚。 使用这些类:函数在Java中使用泛型重载

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"))) 
+6

请将您的代码精简至**所需的最低**数量,以便将问题直接粘贴到您的问题中。 – 2012-03-12 17:09:44

+0

你还没有显示变量'a'和'b'的声明,这是谜题中最关键的部分。如果它是'GBVariable a = new GBFloat(...)',那么行为就像预期的那样。 – 2012-03-12 17:14:59

回答

1

既然你并没有显示出ab我要去猜测的声明,你有

GBVariable<?> a = new GBFloat(...); 
GBVariable<?> b = new GBFloat(...); 

在这种情况下,您所描述的行为是正确的。函数调度(绑定对方法的调用)发生在编译时,使用参数的静态类型。不是运行时类型。

0

方法进行编译的时候,不是运行。这就是为什么直接投射变量时会得到不同的结果。