Class.forName : Java Glossary

*0-9ABCDEFGHIJKLMNOPQRSTUVWXYZ (all)

Class.forName
Uses of Class.forName Sample Code
Under The Hood Finding Classes
Creating Class Objects Warning
Class Instance Methods Limitations
Nested Classes Learning More
Class Names Links
Dynamic Class Loading

Uses of Class.forName

Before I leap into explaining to use Class.forName, I want to give you an idea of what it is for:

Under the Hood

Now let’s look under the hood to understand how the various tools work. There are Class objects (objects of class Class) that represent classes (including arrays), interfaces and primitives. The Class.newInstance method lets you create new objects of that class without requiring a variable declared specifically of that class. You are using the default public no arg constructor. Your class had better have one. This allows code to be much more open ended than in other languages, with new variants added dynamically. The Class.getName method lets you display the class name. There are also methods to discover the details of the fields and methods associated with the class in the java.lang.reflect.* package. Class.forName eagerly loads the class if it not already loaded. Inside the JVM there is a HashMap of all the classes that have been previously loaded. So Class.forName takes under a millisecond if the class you have want is already loaded, If not, it might take 15 milliseconds or so to load it. You pay this time penalty only the first time you use the class. Class.forName is still slower than hard coding the name of the class into your code. With hard coding, you avoid repeated HashMap lookups.

Creating Class Objects

You can’t instantiate Class objects, but most the Class methods are instance methods, not static. So how do you get a Class object:

Class.forName is oblivious to any import statements, so you must fully qualify your class names.

The .class syntax is a kludge, especially double.class. It behaves as though it were a read-only static field even though there is no such field, though obviously there must a hidden pointer in the Class object to the class name.

Class Instance Methods

You can then use methods like Class.toString, Class.getName, Class.getLoader and Class.getSuperclass to tell you even more about Once you have the class, you can then play games with java.lang.reflect.*. Given just the class object, you can find out the constructors, methods, parameters to those methods and the members.

Nested Classes

Inner classes, nested static classes and even anonymous classes all have names which you can determine with Class. getName(). You will discover $ replacing the dots in nested class names, e.g. javax.swing.text.html.HTMLEditorKit$Parser or com.mindprod.americantax.AmericanTax$1. I’m not sure if you could use Class.forName to create instances of inner classes. You can’t create an instance of an inner class without attaching it to an instance of an outer class; I don’t know about Class objects. Please try the experiment and let me know.

Class Names

Dynamic Class Loading

You can also dynamically construct new objects whose implementing code did not even exist at compile time and call methods on those objects.

To keep thing simple, when you have variable classes, they all implement some interface, abstract class or base class, in this case HolInfo:

To go the other way, to get the class name from an object, use obj.getClass().getName().

For a practical example of the technique,

Holiday Calculator: source also uses Class.forName
Learn To Count: source code to allow you to add new language translators or calculators or classes for new holidays, without modifying or recompiling the program; you just add the class names to a properties file
ClassLoader.findLoadedClass will let you find out if a class has already been loaded, without requesting that it be loaded if it is not loaded already.

Sample Code to Dynamically Load Classes

Here is some code that dynamically loads classes, given just the unqualified class name. It looks in two different packages. It caches the classes it finds. The public method returns instances of the named class that implement the Macro interface, not Class objects. This code is the guts of the HTML (Hypertext Markup Language) Static Macros engine. The key tools are Class.forName and Class.

And if this essay did not overamp your brain already, have a look at this code to detect whether a class has been loaded

Finding Classes

If the class you are looking for is on the classpath, you can find out which directory or jar or URL (Uniform Resource Locator) it came from with Sometimes the code may not even have a location, e.g. it was dynamically generated on the fly, either by generating Java source and compiling it with the internal compiling class (sun.tools.javac. Main or generating byte codes on the fly (JASM).

Warning

Limitations

When I first encountered Java, I was very excited about the notion of interfaces and dynamic loading. I thought it would let people plug in their own code to every conceivable utility.

There are two catches:

  1. arranging that java.exe will look for your dynamic class in the place where it is. It will not usually be bundled in the original jar.
  2. arranging that java.exe will look for any auxiliary classes your plug-in needs in the place where they live.

A garden variety jar without a Class-Path entry in the manifest, prevents java from looking anywhere else for classes. The same problem applies to java on other platforms, Java Webstart and the Java Applet plug-in.

How can you get around the problem?

Dynamic class loaders bring with them their own set of problems:

Learning More

Oracle’s Javadoc on Class class : available:
Oracle’s Javadoc on Class.forName : available:
Oracle’s Javadoc on Class.getComponentType : available:
Oracle’s Javadoc on ClassLoader.findLoadedClass : available:

This page is posted
on the web at:

http://mindprod.com/jgloss/classforname.html

Optional Replicator mirror
of mindprod.com
on local hard disk J:

J:\mindprod\jgloss\classforname.html
Canadian Mind Products
Please the feedback from other visitors, or your own feedback about the site.
Contact Roedy. Please feel free to link to this page without explicit permission.

IP:[65.110.21.43]
Your face IP:[34.236.152.203]
You are visitor number