• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dynamic classloading without .forName/.newInstance

 
Andreas Toom
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
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?

/Andreas
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Andreas Toom
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!

/Andreas
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic