编写自定义类加载器时应调用超类的getPermission()函数

在自定义类加载器必须覆盖getPermissions()函数时,在具体实现时,在为代码源分配任意权限前,需要调用超类的getPermissions()函数,以顾及与遵循系统的默认安全策略。忽略了超类getPermissions()方法的自定义类加载器可能会加载权限提升了的非受信类。自定义类加载器时不要直接继承抽象的ClassLoader类。

public class MyClassLoader extends URLClassLoader {

    public MyClassLoader(URL[] urls) {
        super(urls);
    }

    @Override
    protected PermissionCollection getPermissions(CodeSource cs) {
        PermissionCollection pc = super.getPermissions(cs);
        // allow exit from the VM anytime
        pc.add(new RuntimePermission("exitVM"));
        return pc;
    }

    public static void main(String[] args) throws MalformedURLException, IllegalAccessException, InstantiationException, ClassNotFoundException {
        URL[] urls = new URL[]{new URL("file://D:\\cxp\\code\\hello\\src\\")};
        MyClassLoader myClassLoader = new MyClassLoader(urls);
        Class<?> clazz = myClassLoader.loadClass("com.company.Student");
        Object obj = clazz.newInstance();
        System.out.println(obj);
        System.out.println(obj.getClass().getClassLoader());
    }
}

getPermissions()函数调用了super.getPermissions()。结果,除了自定义策略外,系统全局的默认安全策略也被应用。

上面代码运行结果

Student:
name = null
age = null
score = null
com.test.MyClassLoader@3764951d
posted @ 2021-10-15 15:23  衰草寒烟  阅读(3118)  评论(0编辑  收藏  举报