Recipe 25.1 Getting a Class Descriptor


Problem

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

Solution

If the type name is known at compile time, you can get the class instance using the compiler keyword .class , which works on any type that is known at compile time, even the eight primitive types.

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("String[] class: " + String[].class);         System.out.println("Calendar class: " + Calendar.class);         System.out.println("Current class: " + ClassKeyword.class);         System.out.println("Class for int: " + int.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 String[] class: class [Ljava.lang.String; Calendar class: class java.util.Calendar Current class: class ClassKeyword Class for int: int Trying the instance.getClass( ) method: class java.lang.String class java.util.GregorianCalendar C:\javasrc\reflect>

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



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net