Equivalent of the C# keyword 'as' in Java
c#, casting, java
Solution
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
Problem
In Java, is it possible to attempt a cast and get back `null` if the cast fails?