shoosh
shoosh

Reputation: 78914

Equivalent of the C# keyword 'as' in Java

In Java, is it possible to attempt a cast and get back null if the cast fails?

Upvotes: 30

Views: 14481

Answers (9)

Eugene Ryzhikov
Eugene Ryzhikov

Reputation: 17359

You can use the instanceof keyword to determine if you can cast correctly.

return obj instanceof String?(String)obj: null;

Of course it can be genericied and made into the function, but I think question was about what means Java have to accomplish this.

Upvotes: 32

Kathy Van Stone
Kathy Van Stone

Reputation: 26271

You can, but not with a single function in Java:

public B nullCast(Object a) {

  if (a instanceof B) {
     return (B) a;
  } else {
     return null;
  }
}

EDIT: Note that you can't make the B class generic (for this example) without adding the target class (this has to do with the fact that a generic type is not available to instanceof):

public <V, T extends V> T cast(V obj, Class<T> cls) {
  if (cls.isInstance(obj)) {
    return cls.cast(obj);
  } else {
    return null;
  }
}

Upvotes: 5

Harold L
Harold L

Reputation: 5254

The two solutions above are somewhat awkward:

Casting and catching ClassCastException: creating the exception object can be expensive (e.g. computing the stack trace).

The nullCast method described earlier means you need a cast method for each cast you want to perform.

Generics fail you because of "type erasure" ...

You can create a static helper method that is guaranteed to return an instance of your target class or null, and then cast the result without fear of exception:

public static Object nullCast(Object source, Class target) {
    if (target.isAssignableFrom(source.getClass())) {
        return target.cast(source);
    } else {
        return null;
    }
}

Sample call:

Foo fooInstance = (Foo) nullCast(barInstance, Foo.class);

Upvotes: 0

erickson
erickson

Reputation: 269647

public static <T> T as(Class<T> t, Object o) {
  return t.isInstance(o) ? t.cast(o) : null;
}

Usage:

MyType a = as(MyType.class, new MyType());   
// 'a' is not null

MyType b = as(MyType.class, "");   
// b is null

Upvotes: 57

OscarRyz
OscarRyz

Reputation: 199215

MyType e = ( MyType ) orNull( object, MyType.class );
// if "object" is not an instanceof MyType, then e will be null.

...

public static Object orNull( Object o , Class type ) { 
    return type.isIntance( o ) ? o : null;
}

I guess this could somehow done with generics also but I think but probably is not what is needed.

This simple method receives Object and returns Object because the cast is performed in the method client.

Upvotes: 2

Pesto
Pesto

Reputation: 23880

You can either catch the exception:

Foo f = null;
try {
  f = Foo(bar);
}
catch (ClassCastException e) {}

or check the type:

Foo f = null;
if (bar instanceof Foo)
  f = (Foo)bar;

Upvotes: -1

Rony
Rony

Reputation: 9511

you can handle this catching ClassCastException

Upvotes: -2

neesh
neesh

Reputation: 5265

In Java if a cast fails you will get a ClassCastException. You can catch the exception and set the target object to null.

Upvotes: -1

Peter
Peter

Reputation: 6362

AFAIK, this would be (one) of the ways to do that:

SomeClassToCastTo object = null;
try {
  SomeClassToCastTo object = SomeClassToCastTo.class.cast(anotherObject);
}
catch (ClassCastException e) {
  object = null;
}

Ugly, but it should do what you want...

Upvotes: -2

Related Questions