June 2001
Intermediate to advanced
888 pages
21h 1m
English
You want to get a Class object from a class name
or instance.
If the class name is known at compile time, you can get the class
instance using the compiler keyword
.class
, which works on
any object. However, the Object class does not
have class as a field, so this strikes some
observers as a bit of a hack. Nonetheless, it works. Use it.
Otherwise, if you have an object (an instance of a class), you can
call the java.lang.Object method
getClass( )
, which
returns the
Class object for the object’s
class (now that was a mouthful!):
import java.util.*;
/**
* Show the Class keyword and getClass( ) method in action.
*/
public class ClassKeyword {
public static void main(String[] argv) {
System.out.println("Trying the ClassName.class keyword:");
System.out.println("Object class: " + Object.class);
System.out.println("String class: " + String.class);
System.out.println("Calendar class: " + Calendar.class);
System.out.println("Current class: " + ClassKeyword.class);
System.out.println( );
System.out.println("Trying the instance.getClass( ) method:");
System.out.println("Robin the Fearless".getClass( ));
System.out.println(Calendar.getInstance().getClass( ));
}
}When we run it, we see:
C:\javasrc\reflect>java ClassKeyword Trying the ClassName.class keyword: Object class: class java.lang.Object String class: class java.lang.String Calendar class: class java.util.Calendar Current class: class ClassKeyword Trying the instance.getClass( ) method: class ...