Class Object and class Class Two fundamental classes of the Java API
Class Object • Class Object is the root of the object hierarchy • Behavior defined in Object is inherited by all classes • Subclasses are supposed to override most methods (or live with the default implementations) • Some methods of class Object • String toString() • boolean equals(Object obj) • int hashCode() • Class getClass() • Returns an object describing the class of the present object.
class Class • “Instances of the class Class represent classes and interfaces in a running Java application” [Java 2 Platform Standard Edition 5.0 API Specification]. • Instances of class Object are objects. • Instances of class Class are objects describing classes. • Some methods of class Class • static Class<?> forName(String className) • Returns a Class object for the class with the className. • Used in JDBC to load a driver. • T newInstance() • Constructs an object of this class.
Reflection • With the reflection API you can create and manipulate objects of classes where the only thing you have is a String with the name of the class. • Constructing an object from class’ name Class class1 = Class.forName("javax.swing.JButton"); Object obj = class1.newInstance(); • The class must have a no-arg constructor • Used by tools (including NetBeans), servers, etc. to load classes and construct objects from the classes. • Using the reflection API (class Class and other classes) • Constructor getConstructors() • Method getMethods() • FieldgetField(String name) • Package java.lang.reflect
References • Niemeyer & KnudsenLearning Java, 3rd edition, O’Reilly 2005 • 7. Working with Objects and Classes, page 193-213