tags:

views:

44

answers:

1

Hi

I've written some customer class loader that load some classes from a certain directory (that is not in the classpath), say:

class FileSystemClassLoader extends Classloader{
  // implementation details
}

I have some directory say /home/mhewedy/classes/ that is not in the classpath, this directory contains some classes that I use the previous classlaoder to load.

how to use this classloader from the my code to load classes "simplicity" without writing : such code:

Thread.currentThread().setContextClassLoader(new FileSystemClassLoader());
// some code here ...
ClassLoader contextCL = Thread.currentThread().getcontextClassLoader();
+2  A: 

Update to respond to OP edits:

When the JVM loads a class, it will use the classloader that loaded the "current" class (per JVM spec). So if you're in method Foo.main(), which was loaded with your custom classloader, and you want to create an instance of Bar, also loaded via that classloader, you don't have to do anything special.

However, if your current method is Baz.main(), and it was loaded via the system classpath (specified with -cp on the command line), then you have to explicitly load that class via the classloader. There's no way around this. The "context classloader" is meant for application code, to load resources; the JVM ignores it.

In almost all cases, you're better off constructing a classpath that includes your special classes.

Anon
ahh, you mean, if I have class A loaded by my custom classloader, so any class loaded inside A will be loaded by the customer classlaoder ( the parent classloader ), right ?
Mohammed