Tricky Tricks ›› Programming Tricks ›› Java Tricks ›› Class Objects

Class Objects

Java Programming Tricks

Class Objects:

 Objects of type Class are useful to analyze the capabilities of classes, and 
 to generate new objects. In Java 1,0, you could use the forName method to 
 generate an object of a particular class: 
 
 Class cl = Class.forName("java.lang.Double"); 
  
 Tip 
 
 In Java 1.1, you can simply add .class to the name of any type to get the 
 representative class. 
 
 Class cll = Double.class; // it works for classes 
 
 Class c12 = double.class; // it works for numeric types 
 
 Class c13 = double[].class; // it works for arrays 
 
 Class c14 = Cloneable.class; // it works for interfaces 
 
 Sample code: 
 
 Number n = numberFormat.parse (); 
 
 if (n.getClass() == Double.class ) . . .
 
 
 Note 
 
 The Class class should have been called Type since it can represent non-classes
 as well (i.e. numbers and interfaces). Note that arrays are classes in Java.
 

Partners