ClassCastException when casting Object to String, but no ClassCastException when casting Object to Custom class

huangapple go评论51阅读模式
英文:

ClassCastException when casting Object to String, but no ClassCastException when casting Object to Custom class

问题

以下是您要求的翻译内容:

在Java中,我似乎不理解类型转换的基本概念。请解释为什么第一行是有效的,而第二行却无效。

public int compareTo(Object o) {
    Person p = (Person) o; //没有警告
    String s = (String) o; //关于类转换异常的警告
    return 0;
}

这里有什么区别?为什么它允许将对象转换为Person?
英文:

It appears I don't understand basic concept of casting in 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?

答案1

得分: 2

尝试反转:

public int compareTo(Object o) {
    String s = (String) o; //没有警告
    Person p = (Person) o; //关于类转换异常的警告
    return 0;
}

在第二次转换时会收到相同的警告。这是因为 Sonar Linter 关心上下文:它假设如果第一次转换成功,第二次转换将会失败。

英文:

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.

答案2

得分: 0

我认为编译器会允许这样做,就像你说的那样,这只是一个警告。因为将其转换为字符串只有在它实际上是字符串的情况下才会成功。在你的情况下,只有当 o 为 null 时,你的代码才会成功,这可能是你收到这个警告的原因。

英文:

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.

huangapple
  • 本文由 发表于 2020年10月2日 22:53:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/64173700.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定