Java – implement filter class loader

We are extending our Java application to support plug - ins Part of this includes keeping plug-ins isolated from our own classes, so each plug-in will exist in its own class loader

We also plan to provide a Java framework for plug - ins to use, so it must be exposed to plug - ins The Java framework also contains classes that need to be accessed from our own java code, so it must also be able to access our own java code

The problem is that if the Java framework exists in the system class loader (our own java code exists), we can't provide the isolation we want for plug-ins If we choose to separate the Java framework into different class loaders and use it as the parent class of the plug-in class loader, our own classes will not be able to see the Java framework

The current solution I think of is to implement the filter class loader The Java framework will exist in the system class loader, but this class loader will filter out everything in the system class loader. Except for the Java framework, I will use this class loader as the parent class loader of the plug-in

This is a rough implementation:

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;
    }
}

However, I see that it has several problems:

>Just use a separate urlclassloader to see if classes should be filtered. It feels like a hacker attack on me. > When a plug-in loads a class, the class's parent class loader will be the system class loader, which obviously violates all the purposes I want to achieve

How do you solve such problems?

Solution

The OSGi alliance has done it Wikipedia articles about OSGi framework may give you some ideas

You might want to look at the eclipse source code and see how they enable plug - in loading

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>