Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do a safe downcast and prevent a ClassCastException

I have the following scenario:

public class A {
}

public class B extends A {
}

public class C extends B {
    public void Foo();
}

I have a method that can return class A, B or C and I want to cast safely to C but only if the class type is C. This is because I need to call Foo() but I don't want the ClassCastException.

like image 271
code-gijoe Avatar asked Dec 09 '22 14:12

code-gijoe


1 Answers

Can you do this?

if (obj instanceof C) {
   ((C)obj).Foo();
}
else {
   // Recover somehow...
}

However, please see some of the other comments in this question, as over-use of instanceof is sometimes (not always) a sign that you need to rethink your design.

like image 134
Simon Nickerson Avatar answered Dec 12 '22 04:12

Simon Nickerson