我真的试图在这个论坛中寻找这样一个问题的答案,但到目前为止似乎都没有。
我想输入检查方法声明,例如:
public int stackOverFlow() {int a; a = a + 1; return 0;}
返回表达式的类型必须与方法的返回类型匹配(在此示例中为true)。
我使用Java Tree Builder为我的语法中的所有非终端(以节点的形式)和默认的深度优先访问者生成语法树。
我有一个实现Node接口的MethodDeclaration类。节点接口具有以下形式的接受方法:
public Node accept(TypeVisitor v){ return v.visit(v));
此accept方法使TypeVisitor可以访问MethodDeclaration。
现在访问一个方法声明,我做一个简单的类型检查
public Node visit(MethodDeclaration n){
// this visits the f10 Node, which is the return expression,
// and returns a specific Node object
Node rtype = n.f10.accept(this);
// this also does a similar thing by visitng the f1 Node,
// the method's return type, and returns a specific Node Object
Node acType = n.f1.accept(this);
// Now if I compare the two specific Node objects, it always fails.
if(rtype == acType){
//enter here
}
}
为什么不进入if-body?我也试过rtype.equals(acType)
并返回false。
我尝试rtype.toString.equals(acType.toString())
,但也返回false。
我尝试使用eclipse调试器进入代码,这是输出:
rtype IntegerType (id=67)
acType IntegerType (id=69)
从调试器输出可以看出,rtype和acType都是IntegerType对象。
知道比较失败的原因吗?
如果我使用if(rtype instanceof IntegerType),则返回true和
如果我使用if(acType instanceof IntegerType),这也会返回true。
但对象比较总是失败?
我正在使用JavaCC(用于解析器生成),JTB(AST和Visitors创建者),eclipse和java 1.7
答案 0 :(得分:3)
在Java中,==
测试对象标识 - 事实上,这两个对象是同一个对象。您希望使用.equals()
来测试对象相等性。请注意,Object
equals()
中的默认实现只是==
;如果您希望逻辑相等,则您的类必须覆盖equals(Object)
。
有很多资源可供选择。 This article是一个非常好的起点,就像甲骨文的Java tutorial一样。
答案 1 :(得分:1)
我发现了两个潜在的问题:
(1)rtype == acType
很少有你想要的。使用equals
。但既然你告诉过你已经使用过它并没有帮助,这是第二个问题:
(2)equals
的定义不是你想象的那样,或者价值不是你认为的那样。首先,打印rtype.getClass()
和acType.getClass()
以找出对象的确切类型。然后获取这些类的源代码(假设您使用的库是开源的)并查看他们的equals
方法是如何定义的。然后通过equals
方法检查要比较的字段的值。