英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论