Understanding class.Forname
Loading classes Dynamically from With Insions
Abstract
Dynamic loading of Java classes at runtime provides tremendous flexibility in the development of enterprise systems. It provides for the basis of "application servers", and allows even simpler, lighter-weight systems to accomplish some of the same ends. WithinJava, dynamic loading is typically achieved by calling the forName method on the class java.lang.Class; however, when Class.forName is naïvely called from within an Extension, strange errors can occur This paper describes why those errors occur, and how Java2 provides two facilities:. one a modification to the forName syntax, and the other, called the "Thread context ClassLoader", to avoid them. This paper assumes you are passingly familiar with Java Reflection, and have at least a general idea of what Java ClassLoaders are and how they Are used forin java code.
Keywords: Java ClassLoaders Extensions Threads 2
?
Dynamic runtime loading. One of Java's strongest features is its ability to dynamically load code given the name of the class to load, without having to know the actual classname until runtime. This allows Java developers to build flexible, dynamic systems that can grow and change WITHOUT Requiring Complete Recompilation. for Example, The Following Code Executes The Main Method of a class Given on the command-line to the class DynamiCloader:
Public Class DynamiAder
{
Public static void main (string [] args)
Throws Exception
{
Class
Torun
= Class.Forname (Args [0]);
String [] newargs = scrubargs (args);
Method mainmethod = findmain
Torun
);
Mainmethod.invoke (null, new object [] {new mark});
}
Private static string [] Scrubargs (String [] ARGS)
{
String [] Toreturn = New string [args.length-1];
For (int i = 1; i
{
ToreTurn [I-1] = args [i] .tolowercase ();
}
Return ToreTurn;
}
Private Static Method Findmain (Class Clazz)
Throws Exception
{
Method [] methods = Clazz.getMethods ();
For (int i = 0; i
{
IF (Methods [i] .GetName (). Equals ("main")))
Return Methods [i];
}
Return NULL;
}
}
As you can see, DynamicLoader takes the arguments (except the first one) given to it, and passes them directly on to the main method of the loaded class, after first making all the command-line arguments lower case. This means we can run any compiled Java class through DynamicLoader without having to change DynamicLoader's code in the slightest. in fact, we can run any executable Java code, from Swing-based client apps to consolebased Web servers-DynamicLoader really does not care. For example, when we Run The Following Class:
Public Class Echo
{
Public static void main (string args [])
{
For (int i = 0; i
{
System.out.println ("echo arg" i "=" args [i]);
}
}
}
THROUGH DYNAMICLOADER, LIKE THIS:
> Java DynamiAder Echo One Two Three
We get the following output:
Echo arg0 = one
Echo arg1 = two
Echo arg2 = three
As you can see, DynamicLoader created an instance of the Echo class, and called its main method, all without having any direct reference to Echo itself In OO parlance, this means DynamicLoader is completely decoupled from Echo;. There are no explicit dependencies between these two classes. This use of dynamic runtime loading is the heart of Java Application Servers like the Java2 Enterprise Edition reference implementation, Enterprise JavaBeans, and the Servlet Specification. In each one of these architectures, at the time the application server is compiled, it knows nothing about the code that will be attached to it. Instead, it simply asks the user for a classname to load, loads the class, creates an instance of the class, and starts making method calls on that instance. (It does so either through Reflection, or by Requiring That Clients Implement a Particular Interface OR Class, Like GenericServlet in The Servlet Spec, or EJBOBJECT IN THE EJB Spec. is not restricted solely to server-side architectures, however. Web browsers must use it in order to be able to load applets specified by name by a remote web page, as well. RMI uses it to dynamically load stubs and / or skeletons for remote objects, and JNDI and JDBC will use it to load, at runtime, the exact driver necessary (given by the user's appropriate ".properties" file) to perform the work asked. In each case, a ClassLoader is asked to load a class By Name That May Not Have EXISTED WITHIN THE JVM BEFORE this moment.? Enterprise
application architects are also starting to discover ways to put dynamic runtime loading to work for them, as well. For example, several papers and articles have already been published describing how to use XML to create GUI dialogs and / or windows [6], including the ability to instantiate custom classes that did not exist when the basic system was built Class.forName In most of these systems, the code to do the runtime loading comes through the method forName on the class java.lang.Class;.. its use is demonstrated in the previous DynamicLoader code. Class.forName attempts to load the class whose name is given in its only argument, and returns the class instance representing that class. in the event that the class could not be found, resolved, verified, or loaded, Class.forName throws one of several different Exceptions, all of which are listed in the javadoc page for java.lang.Class [1]. Assume for the moment that this DynamicLoader class we've created is a useful bit of functionality , and several other developers have expressed an interest in making use of it. In accordance with the new Java2 emphasis on Extensions, we package DynamicLoader up into a .jar file, and drop it into the Extensions directory of our Java execution environment1. (If you . 're not familiar with Java Extensions, see [1] or [5] for details) The problem comes, however, when we try to execute the Echo class found on the CLASSPATH from within DynamicLoader2:> java DynamicLoader Echo ONE TWO THREE
Exception in thread "main" java.lang.classNotFoundException: echo
AT java.net.urlclassloader $ 1.Run (urlclassloader.java: 2012)
AT java.security.accessController.doprivileged (Native Method)
AT java.net.urlclassloader.findclass (urlclassloader.java: 191) at java.lang.classloader.loadclass (ClassLoader.java: 280)
At java.lang.classloader.loadclass (ClassLoader.java: 237)
At java.lang.class.forname0 (Native Method)
At java.lang.class.Forname (Class.java: 124)
AT DynamiAder.main (DynamiAder.java: 8)
1 Either
/ jre / lib / ext ix
/ LIB / EXT DIRECTORIES, Depending ON WHETHER THE EXECUTING VERSION OF
Java IS
Running Out of the
/ bin Directory or
/ bin.
2 this assumes you've jar'ed DynamiAder.class Into a .jar and place the .jar in the
/ JRE / LIB / EXT
Directory; if you have iten't, do this now.
We can Verify That The Class, Echo, Does in Fact Exist, Either by Running Echo Directly, or by Running The Javap Utility To List ITS Attributes:
> JavaP Echo
Compiled from echo.java
Public Class echo extends java.lang.object {
Public echo ();
Public static void main (java.lang.string []);
}
SO What GIVES? Why is DynamicLoader Failing to Load Echo? What change Between DynamiAder-on-the-classpath and DynamiCloader-as-an-extension?
Problem Analysis
In order to understand precisely what's going on here, you have to understand some of the basics of the Java ClassLoader model and what changed in Java2 from JDK 1.1. Java2 ClassLoader Delegation Model. As described in [2], the Java2 ClassLoader model is a "delegating parent" model, meaning that when a ClassLoader is asked to load a class, it first delegates the opportunity to load the requested class to its parent ClassLoader. Only if the parent (a) has not already loaded the class, and ( b) can not load the Class does the child ClassLoader get the opportunity to provide the Class requested, if it can. This means that ClassLoaders form a hierarchical tree, with the "bootstrap" ClassLoader (the only ClassLoader in the JVM with a " Value "of null) as the root of the tree. (More on the bootstrap classloader.) Any ClassLoader Constructed Wtem Code3 Must Have A Parent ClassLoader;
if none is provided in the ClassLoader constructor call, the ClassLoader constructors assume this ClassLoader's parent to be the "system" or ClassLoader. (More on the "system ClassLoader" later.) Implicitly associated with each loaded Class in a JVM is the ClassLoader that loaded it. It is this ClassLoader that is returned from the Class method getClassLoader. Each Class is associated with one-and-only-one ClassLoader, and this is not mutable-Class objects can not change the ClassLoader reference to point to another ClassLoader . A ClassLoader's loadClass method is called (either directly by the programmer or implicitly by the JVM) when a client wishes to load a class through that ClassLoader. Under the JDK 1.0 and 1.1 models, the ClassLoader directly overrode loadClass to undertake the necessary actions to Load the code. Under JDK 1.2, HoWever, this is no longer the case; instead, the loadclass method / delegate's loadclass to see letter's loadingclass to see letter's loadingclass to see letter's loading lass. Only if the parent (and, by extensions, all of its parental ancestors, as well) fails to load the class does this ClassLoader get the chance to load the code. To do that, it calls the findClass method, which is the Method Customized ClassLoaders Are Now Suppodosed To override.3 That IS, NON-JVM Code.
?
AS An Example of How this Works, Consider a JVM Embedded Inside of A Web Browser. When A Web Page Comes in with an an
. Tag on it, the Web browser constructs an instance of its (vendor-specific) AppletClassLoader This ClassLoader is responsible for obtaining the compiled bytecode from the Website that served the page in the first place; the Web browser simply does something similar to the following :
// Inside the Web Browser Somewhere ...
AppletClassLoader Cl = New AppletClassLoader (AppleTCodebase);
Applet applet = (applet) cl.loadclass (appletClassName) .newinstance ();
Where appletclassname is given within the
HTML Tag. AppletClassLoader, in ITS
loadClass method, first checks with its parent, which under most JVMs will be the primordial ClassLoader. Let's track how this applet's Class gets loaded. Because the system ClassLoader is the parent to the AppletClassLoader, the system ClassLoader is given the opportunity to find the Class . Because the Class code can not be found along the CLASSPATH, in any of the Extensions directories, or in the core library classes (it's an applet, remember the code resides up on the server), the system ClassLoader signals failure. This means IT's now AppletClassLoader's Turn, And It Examines
tag for any information, like CODEBASE attributes, on the whereabouts of the Class file requested. If AppletClassLoader finds a compiled .jar or .class file, it downloads the code as a binary file and loads it into the JVM (via the
DefineClass Method ON ClassLoader) from the Web Browser Can Now Construct An Instance of The Applet Class, Because Now It Has The Requested Class File Loaded Into ITS JVM: IT CAN NOW CALL THE
Start,
stop, and other methods on Applet. This parent-child relationship of Java2 now releases Java ClassLoader developers from having to remember to check the system ClassLoader to see if the class has already been loaded. More importantly, however, it permits a "chain- loading "of classes from a variety of sources. For example, in a hypothetical enterprise system, I might create a JDBCClassLoader, whose parent is a URLClassLoader pointing to an HTTP server inside my corporate firewall. That URLClassLoader in turn is a child of the primordial ClassLoader. This provides me a three-layered, code-loading facility, where rapidly-changing code, such as business rules (sales promotionals and the like) can be stored in the RDBMS, potentially on a user-by-user basis, if necessary. The less-mutable code is stored on my HTTP server, and the system and bootstrap ClassLoaders are responsible for the core Java classes, as usual. This approach allows the more stable code to "override" more mutable behavior ;. If you desire the opposite, simply reverse the placement of the JDBCClassLoader and the URLCLassLoader In each case, because the nature of the ClassLoading mechanism is "parent-first", whichever ClassLoader is highest up on the hierarchy has "classloading priority" over . its children Because each child delegates to its parent, we will load code in top-down order;. in the fictitious aforementioned example, the system ClassLoader gets the first chance, followed by the URLClassLoader, followed by the JDBCClassLoader Understanding how the system ClassLoader Is Architected, Along With Understanding of the "Parent-First" Nature of Delegating ClassLoaders, Yields Discovery of The Problem.?
Java2 / JDK1.2 Default ClassLoader architecture The Java2 system provides for loading code from one of three places by default:. The core library, the Extensions directory (or directories, if you modify the java.ext.dirs property to include multiple subdirectories) ., and from the directories and / or .jar / .zip files found along the java.class.path property, which in turn comes from the CLASSPATH environment variable Each of these three locations is in turn covered by its own ClassLoader instance: the core classes, by the bootstrap ClassLoader, the Extensions directory / directories by the extension ClassLoader, and the CLASSPATH by the system or application ClassLoader4 Before we delve too deeply into this, let's run a quick test Compiling and executing this code:.. public class EchoclassLoader
{
Public static void main (string args [])
{
ClassLoader Current =
New echoclassloader (). getClass (). getClassLoader ();
While (current! = null)
{
System.out.println (Current.getClass ());
Current = current.getParent ();
}
}
}
Products this Rather Interesting Result:
> Java EchoclassLoader
Class Sun.Misc.launcher $ AppClassLoader
Class Sun.misc.launcher $ EXTCLASSLOADER
The result highlights something very interesting I've been speaking of the system ClassLoader as a singular entity, but there are two parents to our class' ClassLoader:. One called Launcher $ AppClassLoader, and one called Launcher $ ExtClassLoader, both of which live in the sun.misc package. The bootstrap ClassLoader is implemented as part of the VM itself, and can not be instantiated by Java code. It is this ClassLoader that brings the core Java classes into the VM, allowing the rest of the JVM to load itself. (Take a second to think about this-in order to construct a ClassLoader, which extends Object, the JVM must load the Object class. But in order to do this, it requires a ClassLoader with which to load it!) Normally, this means Loading code from the "rt.jar" File in the JDK / JRE / LIB Subdirectory, But under the sun jvm, the boot.class.path protection actry controls it5.4 At One Point, During The JDK 1.2 Beta3 Release, IT WAS Also Called The Base ClassLoader.
5 Why this could be important is beyond the scope of this paper.
?
The extension ClassLoader, the first child of the boostrap ClassLoader, is implemented in pure Java code. As already mentioned, the extension ClassLoader's primary responsibility is to load code from the JDK's extension directories. This in turn provides users of Java the ability to simply " drop in "new code extensions (hence the name" Extension directory "), such as JNDI or JSDT, without requiring modification to the user's CLASSPATH environment variable. The system, or application, ClassLoader is the ClassLoader returned from the static method ClassLoader.getSystemClassLoader . This is the ClassLoader responsible for loading code from the CLASSPATH, and by default will be the parent to any user-created or user-defined ClassLoader in the system. (As an aside, both of these classes are direct descendants of URLClassLoader. ExtClassLoader Reads The Java.ext.dirs Property For A List of Directories. IT Takes Each Directory In Turn, Item Over Each File In The Directory, Builds a URL OUT of it, and stores that URL in the URLClassLoader-parent portion of itself. ExtClassLoader also overrides the findLibrary method to search the directory given by This allows extension directories the property os.arch under each extension directory for the library matching the requested name. to also silently support native-libraries in the same "drop-in" manner as Extensions themselves. AppClassLoader reads the java.class.path property, and for each File.pathSeparator-separated entry, builds a URL out of it. Once these two classes Are Created, However, They Behave In All Respects Like A Standard UrlclassLoader. There Two Classes, Along with UrlclassLoader, Are Described More Fully In [5].
So now we have some deeper insight into the architecture of the ClassLoader system in Java2. Let's take a moment and see, step-by-step, why Class.forName, when called on a class found within the CLASSPATH, fails when called from within An extension.to summarize the "normal" ClassLoader Tree:
Bootstrap ClassLoader
Type: None; Implement within the VM
Parent: None
Loads Core Runtime Library Code from Sun.Boot.class.Path
Extension ClassLoader
TYPE: Sun.misc.launcher $ EXTCLASSLOADER
Parent: NULL (Bootstrap ClassLoader)
Loads Code Found in Extension Director (Given By Java.ext.dirs)
System (or Application) ClassLoader
TYPE: Sun.misc.launcher $ AppClassLoader
Parent: Extension ClassLoader
Returned from ClassLoader.getsystemClassLoader
Loads Code Found on java.class.path (The ClassPath Variable)
?
Calling class.forname within an extension. Go back to the Original Problem: this
CODE:
Public Class DynamiAder
{
Public static void main (string [] args)
Throws Exception
{
Class
Torun
= Class.Forname (Args [0]);
String [] newargs = scrubargs (args);
Method mainmethod = findmain
Torun
);
Mainmethod.invoke (null, new object [] {new mark});
}
//.
}
When Called from Withn Extension, Fails with:
> Java DynamiAder Echo One Two Three
Exception in thread "main" java.lang.classNotFoundException: echo
AT java.net.urlclassloader $ 1.Run (urlclassloader.java: 2012)
AT java.security.accessController.doprivileged (Native Method)
AT java.net.urlclassloader.findclass (urlclassloader.java: 191)
AT java.lang.classloader.loadclass (ClassLoader.java: 280)
At java.lang.classloader.loadclass (ClassLoader.java: 237)
At java.lang.class.forname0 (Native Method)
At java.lang.class.Forname (Class.java: 124) at DynamiAder.main (DynamiAder.java: 8)
. Walking through the Class.forName call highlights the problem Class.forName obtains the caller's ClassLoader, and uses that ClassLoader instance to load the Class into the VM Written in pseudoc ode, Class.forName looks like.:
Public Class Forname (String Classtoload)
.
{
ClassLoader Cl = ClassLoader.getCallerClassLoader ();
Return Cl.LoadClass (Classtoload);
}
It's fairly easy, now, to spot what the problem is. When a Class is loaded from the CLASSPATH, its associated ClassLoader is the AppClassLoader instance. When that Class invokes Class.forName, it can find other classes along the CLASSPATH or in the Extensions Directory Because AppClassLoader First Delegates To Its Parent, The ExtclassLoader. Only If The Requested Class Is Not Found as an Extension Is The ClassPath Searched.
?
When the Calling Class Is Loaded As An Extension, However, ITS Associated ClassLoader Is The ExtClassLoader. Thus, When the Extension-loaded class calls class.forname,
1. The Caller's ClassLoader Is Obtained; In this case, That Caseloader is The ExtclassLoader Instance.
2. The ExtClassLoader, Being a Good Child, Gives ITS Parent, The Bootstrap ClassLoader, The Opportunity To Load The Class.
3. Because The Bootstrap ClassLoader Fails To Find It in JDK / JRE / LIB / RT.JAR, IT RETURns WITHOUT A LOAD Class.
4. ExtClassLoader's loadClass method the load then attempts to load the Class from within its list of URLs (given, as described earlier, in the java.ext.dirs property). Because the class is not within the list of URLs associated with ExtClassLoader, Fails, And a classnotfoundexception is thrown.
PUT Simply, Because Extension-loaded classloader instance anywhere on their parent-classloader chain, They can't load any class off of the classpath.solution
Fundamentally, there are two solutions available to you: use a different form of the forName method on Class, or use a ClassLoader associated with each specific Thread, called the Thread's context ClassLoader As with everything, each approach has its own consequences Use Thread.. . .getContextClassLoader A new concept introduced in Java2, each Thread now has a context ClassLoader associated with it Looking at the javadocs [1] for the Thread methods getContextClassLoader and setContextClassLoader reveals that Thread.getContextClassLoader:. Returns the context ClassLoader for this Thread The. context ClassLoader is provided by the creator of the thread for use by code running in this thread when loading classes and resources. If not set, the default is the ClassLoader context of the parent Thread. The context ClassLoader of the primordial thread is typically set to THE CLASS Loader Used to Load The Application. Thread.SetContextClassLoader: Sets The Context ClassLoader for this Thread. The Context ClassLoader Can Be Set WHEN A Thread Is Created, And Allows The Creatries Class Loader To Code Running In The Thread When Loading Classes and Resources.