开发者

Implicity usage of Java Custom class loaders?

开发者 https://www.devze.com 2022-12-23 03:37 出处:网络
I\'ve written some customer class loader that load some classes from a certain directory (that i开发者_如何转开发s not in the classpath), say:

I've written some customer class loader that load some classes from a certain directory (that i开发者_如何转开发s 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();


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消