eugene p
eugene p

Reputation: 7

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. 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?

Upvotes: 0

Views: 145

Answers (2)

Semaphor
Semaphor

Reputation: 1040

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.

Upvotes: 0

Philippe Escure
Philippe Escure

Reputation: 149

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.

Upvotes: 2

Related Questions