使用==运算符编译错误

时间:2013-01-07 01:38:16

标签: java equivalence

我已将错误隔离到此行: string.getClass()== jojo.getClass() 这行不应该创建两个Class对象,然后检查它们(如在两个引用中)是否指向同一个对象?代码不会返回false值,而是不会运行。

public class Tester 
{
    public static void main(String[] args) 
    {
        OreoJar jojo = new OreoJar(0);
        OreoJar momo = new OreoJar(1);
        String string = "Hello";

        if (momo.getClass() == jojo.getClass())
        {
            System.out.println("Momo and jojo are of the same class");
        }

        if (string.getClass() == jojo.getClass())
        {
            System.out.println("String and jojo are of the same class");
        }
    }
}

public class OreoJar 
{
    int oreos;

    public OreoJar(int oreos)
    {
        this.oreos = oreos;
    }

    public void count()
    {
        System.out.println(oreos + " oreos in this jar!");
    }
}

这个评论有点隐藏,我觉得它值得一提,因为它对初学者(比如我自己)最有意义

- 根据JLS“如果无法通过转换转换将任一操作数的类型转换为另一个的类型,那么这是编译时错误”,因此如果可以比较类型A和B的两个引用,则,只有当A可以投射到B或B时才可以投射到A. - Patricia Shanahan

3 个答案:

答案 0 :(得分:6)

我同意OP应该引用编译错误。

无论如何,当任何人实际进行编译时,编译错误是非常明显的。

错误是:

Tester.java:15: incomparable types: java.lang.Class<capture#125 of ? extends java.lang.String> and java.lang.Class<capture#29 of ? extends OreoJar>
    if (string.getClass() == jojo.getClass()){
                          ^

原因显而易见。

来自Object.getClass()的Javadoc:

The java.lang.Class object that represents the runtime class of the
object. The result is of type Class<? extends X> where X is the
erasure of the static type of the expression on which getClass is
called.

这意味着,String实例将返回对Class<? extends String>的引用,而OreoJar实例将返回对Class<? extends OreoJar>的引用

这两种类型根本不兼容,因为编译器知道扩展String的任何类型都不可能是类型扩展OreoJar。因此,比较将导致编译错误。


有点偏离主题,但我认为值得一提,你说:

  

此行不应该创建两个Class对象,然后检查它们是否指向同一个对象

我认为最好有更清楚的理解。它不会“创建”两个Class 对象。 getClass()将返回一个引用到Class对象。并且,始终是引用可以指向对象,而不是对象指向对象(它听起来也很奇怪)

答案 1 :(得分:3)

我认为它不会编译的原因是由于Class有通用组件。尝试使用momo.getClass().equals(jojo.getClass()) 您也可以尝试比较类的规范名称以获得类似的效果:momo.getClass().getCanonicalName().equals(jojo.getClass().getCanonicalName())

答案 2 :(得分:-1)

getClass()返回Class的实例。 getClass().getName()返回一个字符串。 String.equals(otherString)方法是比较字符串是否相等的正确方法。