File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Dynamic classloading without .forName/.newInstance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Dynamic classloading without .forName/.newInstance" Watch "Dynamic classloading without .forName/.newInstance" New topic

Dynamic classloading without .forName/.newInstance

Andreas Toom

Joined: Feb 10, 2005
Posts: 4
I've successfully written my own network class loader and it works fine when doing something like this:

NetworkClassLoader loader = new NetworkClassLoader();
Class classClass = loader.loadClass( "com.test.classes.TestClass" );
Object obj = classClass.newInstance();

This is some research coding for a current project that will move from a rather fat client to a thinner one with class loading from a single repository. This means that the current client code is full of new MyClassThis() and new MyClassThat( param1, param2 ) and so on.

My initial thought was that Thread.currentThread.setContextClassLoader( new NetworkClassLoader() ) would take care of this and ALL classes not found in the current classpath would be redirected to my custom class loader but that is apparently not the case, my class loader is being completly ignored when "new" is used. Is there some way to tell the jvm to use my class loader when looking for classes or do I have to look at another solution with jar:s and URLClassLoader instead?

Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
This is just from eavesdropping on prior threads and scanning the doc ...

Every class has a reference to the ClassLoader that defined it and uses that for "new" operations. Any additional classloaders chain to some parent. So if your program main() used your custom class loader to load the first class, you'd be in the chain of loaders from then on.

ClassLoaders delegate to their parent loaders BEFORE they attempt to load something. I guess your special classes are not in the normal classpath so the parent will fail and then you get your chance.

Does that sound reasonable?

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Andreas Toom

Joined: Feb 10, 2005
Posts: 4
Made a quick test and it worked out real nice, I should be able to build something that suits our needs. Thanks for the help!

I agree. Here's the link:
subject: Dynamic classloading without .forName/.newInstance
jQuery in Action, 3rd edition