简体   繁体   English

将 Object 转换为 String 时出现 ClassCastException,但将 Object 转换为自定义类时没有 ClassCastException

[英]ClassCastException when casting Object to String, but no ClassCastException when casting Object to Custom class

It appears I don't understand basic concept of casting in Java.看来我不了解 Java 中强制转换的基本概念。 Please explain why first line is valid and second is not请解释为什么第一行有效而第二行无效

  public int compareTo(Object o) {
        Person p = (Person) o; //no warning
        String s = (String) o; //warning about class cast exception
        return 0;
    }

What is the difference here?这里有什么区别? Why it allows cast object to person?为什么它允许将对象强制转换为人?

Try inverting :尝试反转:

public int compareTo(Object o) {
    String s = (String) o; //no warning
    Person p = (Person) o; //warning about class cast exception
    return 0;
}

You'll get the same warning on the second cast.您将在第二次转换时收到相同的警告。 This is because the sonar linter care about the context : it assume that if your first cast succeeed the second will fail.这是因为声纳 linter 关心上下文:它假设如果您的第一个演员成功第二个将失败。

I think the compiler will allow this as you said its only a warning.我认为编译器会允许这样做,因为你说它只是一个警告。 As a cast to a String will only succeed in case its actually a String.作为对字符串的强制转换只有在它实际上是字符串的情况下才会成功。 In your case, your code will only succeed if o is null, that's probably the reason you get this warning.在您的情况下,您的代码只有在 o 为空时才会成功,这可能是您收到此警告的原因。

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

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