有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java实现过滤类装入器

我们正在扩展java应用程序以支持插件。其中的一部分包括保持插件与我们自己的类隔离,这样每个插件都将生活在它自己的类加载器中

我们还计划为插件提供一个java框架来使用,因此它必须向插件公开。这个java框架还包含需要从我们自己的java代码访问的类,因此它也必须可以从我们自己的java代码访问

问题是,如果java框架存在于系统类装入器中(我们自己的java代码所在的地方),我们就不能给插件提供我们想要的隔离。如果我们选择将java框架分离到不同的类加载器,并将其用作插件类加载器的父类,那么java框架对我们自己的类将不可见

我想到的当前解决方案是实现一个过滤类装入器。java框架将存在于系统类加载器中,但是这个类加载器将过滤系统类加载器中的所有内容,java框架除外,我将使用这个类加载器作为插件的父类加载器

下面是它的一个粗略实现:

public class FilteringClassLoader extends ClassLoader {
    private URLClassLoader _internalLoader;

    public FilteringClassLoader(ClassLoader parent) {
        super(parent);

        // load our java framework to this class loader
        _internalLoader = new URLClassLoader(...)
    }

    public Class<?> loadClass(String name) throws ClassNotFoundException {
        // first, try to load from our internal class loader
        // that only sees the java framework if that works, load the class 
        // from the system class loader and return that. otherwise, the class 
        // should be filtered out and the call to loadClass will throw as expected
        _internalLoader.loadClass(name);

        Class<?> retClazz = super.loadClass(name);

        return retClazz;
    }
}

然而,在我看来,这有几个问题:

  1. 在我看来,使用单独的URLClassLoader只是为了查看类是否应该被过滤,这就像是一种黑客行为
  2. 当插件加载一个类时,该类的父类加载器将是系统类加载器,这显然违背了我试图实现的全部目的

你如何解决这类问题


共 (2) 个答案

  1. # 1 楼答案

    If we choose to separate the java framework to a different class loader and use that one as the parent of the plugins class loader, the java framework won't be visible to our own classes.

    将代码放在一个类加载器中,该类加载器是插件类加载器的对等体,两者都以接口代码类加载器作为父级

  2. # 2 楼答案

    How do you solve this kind of problem?

    OSGi联盟已经做到了。维基百科关于OSGi framework的文章可能会给你一些想法

    您可能希望查看Eclipse的源代码,并了解它们是如何实现插件加载的