Alex Rivera | Logout

How to emulate C# as-operator in Java

Asked 2008-09-29T14:11:56.647
57

There are situations, where it is practical to have a type-cast return a null value instead of throwing a ClassCastException. C# has the as operator to do this. Is there something equivalent available in Java so you don't have to explicitly check for the ClassCastException?

Edit
Report

1 Answer

15

You can use the instanceof keyword in place of C#'s is, but there is nothing like as.

Example:

if(myThing instanceof Foo) {
   Foo myFoo = (Foo)myThing; //Never throws ClassCastException
   ...
}
answered 2008-09-29T14:14:14.333

Your Answer