How can I make a safe click and prevent a ClassCastException

I have the following script:

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

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

+4
source share
4 answers

Can you do it?

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

However, please check out some other comments on this question, as excessive use of instanceof sometimes (not always) means you need to rethink your design.

+6
source

You can check the type before casting with instanceof

 Object obj = getAB_Or_C(); if ( obj instanceof C ) { C c = (C) obj; } 
+2
source

What you have to do is something like the following, then you do not need to quit.

 public class A { public void foo() { // default behaviour. } } public class B extends A { } public class C extends B { public void foo() { // implementation for C. } } 
+2
source

As an alternative to instanceof consider

 interface Fooable { void foo(); } class A implements Fooable { ... } 
+2
source

All Articles