Java – 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?

Best Solution

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


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

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