Is it possibly in java to attempt a cast and get a null if the cast fails?
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.
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...
In Java if a cast fails you will get a ClassCastException. You can catch the exception and set the target object to null.
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;
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;
}
}
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.
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
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);