In Java, is it possible to attempt a cast and get back null
if the cast fails?
9 Answers
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
-
@erickson: This is perfect! +10 if I could ( I knew generic could be used here :P ) I added a sample usage , feel free to rollback if you feel like. – OscarRyz Jun 23 '09 at 18:37
-
2Good design, but isn't it better to use `isAssignableFrom` in cases like this. – C. Ross Nov 01 '11 at 13:50
-
@C.Ross You mean `t.isAssignableFrom(o.getClass())`? Why would that be better? – erickson Nov 01 '11 at 16:28
-
1@erickson It just handles a few more edge cases. See [Q496928](http://stackoverflow.com/questions/496928) – C. Ross Nov 01 '11 at 16:52
-
@C.Ross I don't see any edge cases in that question that are not handled by `isInstance()`. However, I do see that the null checking required by `isAssignableFrom()` would add unnecessary complication. – erickson Nov 01 '11 at 16:57
-
I like the design of the above function `as`, but it bothers me the fact that the `isInstance` method will be invoked twice, due to the use of the `cast` method of the class `Class`. Internally, this method uses the `IsIsntance` method to check for compatibility between types. Nevertheless, we can expect that the JVM may inline the `cast` code inside the given `as` function and after that the Jitter may remove redundant calls to the `IsInstance` method, but we cannot be sure about that. – Miguel Gamboa Jan 09 '13 at 19:21
-
The "as" keyword will work even if the input object is not an instance of the requested type -- if there is any possible conversion, it will take it. I'm new to Java, but will the above code do that? If not, it may be that @C.Ross has a valid point. Still though, checking for null is also required (and not that complicated). – BrainSlugs83 Jul 30 '13 at 22:28
-
1@BrainSlugs83 It sounds like this method falls a bit short of the real `as` operator then, because it will not perform any sort of type coercion. As for C. Ross's comment, his suggestion has nothing to do with that issue, and he failed to explain any benefit in it. – erickson Jul 30 '13 at 23:47
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.

- 17,131
- 3
- 38
- 60
-
1I'm not sure that's what shoosh wants. Probably a more generic way to treat the cast is needed. This would be the perfect answer for "How do I validated my object is instance of a given class" though :) – OscarRyz Jun 23 '09 at 18:26
-
1I think we are not here to solve problems for others, but provide guidance. So pointing the right direction should be enough. – Eugene Ryzhikov Jun 23 '09 at 23:45
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;
}
}

- 25,531
- 3
- 32
- 40
-
Yes, but I was giving the general idea, not a specific method. – Kathy Van Stone Jun 23 '09 at 18:35
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.

- 196,001
- 113
- 385
- 569
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...

- 6,354
- 1
- 31
- 29
-
That's not a good case for using the reflective "cast()" method. See http://stackoverflow.com/questions/243811/when-should-i-use-the-java-5-method-cast-of-class for more info. – erickson Jun 23 '09 at 18:24
-
-
1creating an exception in this case could be avoided. exceptions are objects, so it's nice not to create them unnecessarily. – cd1 Jun 23 '09 at 18:36
In Java if a cast fails you will get a ClassCastException. You can catch the exception and set the target object to null.

- 5,167
- 6
- 29
- 32
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;

- 23,810
- 2
- 71
- 76
-
3Empty catch blocks are a very bad habit... actually, I think the compiler should slap you in the face when you do it ;). And anyway, you should never rely on exceptions for something you can check without an exception being thrown. – Thomas Levesque Jun 23 '09 at 18:26
-
2
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);

- 5,166
- 28
- 28
you can handle this catching ClassCastException

- 9,331
- 2
- 22
- 22
-
2Every time an Exception gets thrown, there's a lot of overhead involved. That's why Exceptions should be just that--an "exception." Exception handling should be reserved for events that are truly exceptional. When exceptions become the rule, you're programming wrong. Far better to use type checking. – StriplingWarrior Jun 23 '09 at 19:48