Next page | Contents page |

The class called Class

There is an instance of java.lang.Class in the JVM for every class used so far in executing an application. It is responsible for instantiating objects of the class and for reflection (finding out about the class at run time).

Example of reflection:

	java.util.Date d = new java.util.Date ();  // Gets current time & date
	Class c = d.getClass ();	       // Every object has getClass ()
	System.out.println (c.getName ()); // -> "java.util.Date"
	java.lang.reflect.Field [] fs = c.getFields ();
	java.lang.reflect.Method [] ms = c.getMethods ();
	java.lang.reflect.Constructor [] cs = c.getConstructors ();

	for (java.lang.reflect.Method m : ms)
	{
		System.out.println (m); // Try this on any class!
	}
	
	// etc - similar for fields and constructors

The class literal

Appending .class to any type name (class, array, interface or primitive type or even pseudo-type void) gets a reference to its class object. Eg, double.class gets the class object for java.lang.Double. (In Java 5 this is consistent with the auto-boxing process.)

So void and interface types have class objects in the JVM too!

Next page | Contents page |