Getting a Class Descriptor

Problem

You want to get a Class object from a class name or instance.

Solution

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
eflect>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 java.lang.String 
class java.util.GregorianCalendar
C:javasrc
eflect>

Nothing fancy, but as you can see, you can get the Class object for any class known at compile time, whether part of a package or not.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.173.199