Java Reference
In-Depth Information
16.1.6. Runtime Type Queries
When writing your programs you can check the type of an object by us-
ing instanceof or change the type of an expression with a cast. In both
cases you need to know the name of the type involved so you can write
it in the code. When working with reflection, you have only Class objects
to work with, so operators like instanceof and casts can't be used. The
class Class provides several methods that provide functionality analog-
ous to the language level operators:
public boolean isInstance(Object obj)
Determines if obj is assignment compatible with this class.
This is the dynamic equivalent of the instanceof operator. It
returns true if obj could be assigned to a variable of the type
represented by this Class object; and false otherwise.
public T cast(Object obj)
Casts the object obj to the type represented by this Class ob-
ject. If the cast fails then ClassCastException is thrown. This is
needed in some rare circumstances when the type you want
to cast to is represented by a type parameter and so you can't
use an actual language-level cast.
public boolean isAssignableFrom(Class<?> type)
Returns true if this Class object represents a supertype of type
or type itself; otherwise returns false .
 
Search WWH ::




Custom Search