0

我真的尝试在这个论坛中寻找这样一个问题的答案,但到目前为止似乎没有一个工作。

我想键入检查方法声明,例如:

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));

此接受方法使 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 和访客创建者)、eclipse 和 java 1.7

4

2 回答 2

3

在 Java 中,==测试对象身份——两个对象实际上是同一个对象。您想用来.equals()测试对象是否相等。请注意,默认实现 (in Objectofequals()很简单==;如果您想要逻辑相等,您的类必须覆盖equals(Object).

有很多关于如何做到这一点的资源。本文是一个很好的起点,Oracle 的Java 教程也是如此。

于 2013-04-14T20:14:41.897 回答
1

我看到两个潜在的问题:

(1)rtype == acType很少是你想要的。使用equals. 但是既然你告诉过你已经使用过它并且它没有帮助,那么这是第二个问题:

(2) 要么的定义equals不是你想象的那样,要么价值观不是你想象的那样。首先,打印rtype.getClass()acType.getClass()找出对象的确切类型。然后获取这些类的源代码(假设您使用的库是开源的)并查看它们的equals方法是如何定义的。然后继续检查该方法正在比较的字段的值equals

于 2013-04-14T20:35:40.117 回答