Saturday, 9 August 2008

What does the Class Class implement and extend?

This refers to java.lang.Class. Here's the declaration:

public final class Class
extends Object
implements Serializable

To print out the class name of an object you can do:

obj.getClass().getName()

Another common sight is calling the static method forName which returns the Class object (a.k.a. runtime class descriptor) associated with the given string name. By default, forName uses the class loader of the current class. If the class cannot be found, a ClassNotFoundException is thrown. forName can also throw a LinkageError and ExceptionInInitializer error.

In order to return the class object (or class descriptor) the class needs to loaded, linked and initialized. Thus Class.forName is sometimes used just to load and link a class then throw away the returned object.

The Class Class also contains boolean methods like isInterface and isPrimitive.

No comments:

Blog Archive