views:

326

answers:

2

I'm using rhino via the bean scripting framework to create and configure objects in my java process. Some of the classes used in the scripts need to be loaded dynamically as they won't always be on the standard classpath.

To load these classes I initialize the scripting framework's context factory with a custom class loader that loads these classes from an auxilary directory. This works well.

The problem is that some of these classes, in their constructors, use other classs which must also be loaded from this auxilary directory. Looking at the source I see that the javascript engine is simply calling Constructor.newInstance.

How do I know which classloader the newInstance call uses, and can I inject my own so I can manually load classes that the standard class loader doesn't know how to load.

+1  A: 

Try setting the parent classloader of your class loader to the application classloader.

ClassLoader myLoader = new ClassLoader(getClass().getClassLoader()) { 
... your code loading from custom directory ...
}

The classes loaded from your loader will use your loader to lookup other classes, so your loader needs to provide those (by delegating to the parent)

ankon
A: 

Constructor.newInstance operates upon a Constructor instance, which belongs to a particular Class instance which was loaded by a particular ClassLoader. Classes link through their own class loader.

Single-arg Class.forName uses the immediate caller's class loader (it is a very naughty API).

Tom Hawtin - tackline