且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用自定义ClassLoader?

更新时间:2023-02-25 21:15:54

我不明白这个问题,你有第三方库,你希望它使用你的类加载器加载类。

Not sure I understand the question, you have a 3rd party lib and you want it to use your classloader to load classes.

如果你很幸运,第三方lib使用线程上下文类加载器,您可以使用 Thread.currentThread()。setContextClassLoader(myClassLoader)$设置c $ c>,在同一个线程中,您可以使用 Thread.currentThread()。getContextClassLoader() ...

If you're lucky the third party lib uses the threads context classloader which you can set using Thread.currentThread().setContextClassLoader(myClassLoader), in the same thread you can access this classloader with Thread.currentThread().getContextClassLoader()...

另一点,但不确定它在您的上下文中是否重要,是你还可以编写一个父 - 最后一个类加载器,它将在委托给它的父代之前尝试加载该类(而不是先尝试委托)

Another point, but not sure it is important in your context, is that you can also write a parent-last classloader that will try to load the class before delegating to its parent (instead of trying to delegate first)

已编辑在您的评论之后:

如果您的库不依赖于线程上下文类加载器,则parent_last类加载器会有所不同,那么您必须加载库你的父级最后一个类加载器因此将你的类加载器设置为库的类加载器而不是它的父加载器(类加载器的父级)......

parent_last classloader will make a difference if your library doesn't rely on the thread context classloader, then you have to load the library with your parent-last classloader thus setting your classloader as the classloader for the library instead of its parent loader (the parent of your classloader)...

你也可以制作一个classloader具有父亲优先行为,但适用于您的第三方库...

You may also make a classloader with a parent-first behavior but for your 3rd party library...

关于类加载器的一个很好的链接......