The instanceof
operator is the handiest way to do runtime type checking:
if (someObject instanceof String) {
// It's a string
}
Alternately, on any instance, you can use getClass
, which gives you the Class
instance for the type of the object.
Class c = someObject.getClass();
The Class
instance will have a getName
method you can call to get a string version of the name (and lots of other handy methods).
You can get a Class
object from a type name using .class
, e.g.:
Class stringClass = String.class;
As Peter Lawrey points out in the comments, all of these assume you're dealing with an object reference, not a primitive. There's no way to do a runtime type check on a primitive, but that's okay, because unlike with object references (where your compile-time declaration may be Object
), you always know what your primitive types are because of the declaration. It's only object types where this really comes up.
If you find yourself doing a lot of explicit type checks in your Java code, that can indicate structure/design issues. For the most part, you shouldn't need to check type at runtime. (There are, of course, exceptions.)