[ACCEPTED]-Equivalent of the C# keyword 'as' in Java-casting

Accepted answer
Score: 56
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

0

Score: 30

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

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

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

Score: 5

You can, but not with a single function 5 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 4 B class generic (for this example) without 3 adding the target class (this has to do 2 with the fact that a generic type is not 1 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;
  }
}
Score: 2
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 4 generics also but I think but probably is 3 not what is needed.

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

Score: 0

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

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

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

Score: 0

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

Score: 0

You can either catch the exception:

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

or check 1 the type:

Foo f = null;
if (bar instanceof Foo)
  f = (Foo)bar;
Score: 0

The two solutions above are somewhat awkward:

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

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

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

You 5 can create a static helper method that is 4 guaranteed to return an instance of your 3 target class or null, and then cast the 2 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 1 call:

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

More Related questions