简体   繁体   English

发生了什么样的异常?

[英]What kind of Exception occurred?

I tried to create a test ClassCastException: 我试图创建一个测试ClassCastException:

In line 1: it prints out class cast exception as I expected 在第1行:它按照我的预期打印出class cast exception
In line 2: it just prints exception.RuntimeExceptionTest$1B@7852e922 (RuntimeExceptionTest is my class name). 在第2行:它只打印exception.RuntimeExceptionTest$1B@7852e922 $ 1B@7852e922(RuntimeExceptionTest是我的类名)。 I wonder what kind of exception here? 我想知道这里有什么样的例外?

 try {
            class A { }
            class B extends A {}
            class C extends A {}
            A objA = new B();
            System.out.println((C)objA); // Line 1
            System.out.println((A)objA); // Line 2
        } catch (Exception e) {
            e.printStackTrace();
        }

Line2 doesn't throw an exception. Line2不会抛出异常。 From the Oracle javadocs: 来自Oracle javadocs:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. 类Object的toString方法返回一个字符串,该字符串由对象为实例的类的名称,符号字符“@”和对象的哈希码的无符号十六进制表示组成。 In other words, this method returns a string equal to the value of: 换句话说,此方法返回一个等于值的字符串:

 getClass().getName() + '@' + Integer.toHexString(hashCode())

That means your Line2 just prints what objA.toString() returns, which is 这意味着你的Line2只打印objA.toString()返回的内容,即

 exception.RuntimeExceptionTest$1B@7852e922

since exception.RuntimeExceptionTest is your class name. 因为exception.RuntimeExceptionTest是你的类名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM