Exception in thread "main" java.lang.SecurityException: Prohibited package name:

时间:2022-10-11 23:04:54

Exception in thread “main” java.lang.SecurityException: Prohibited package name:java.


随便写Demo的时候突然发生这个异常,这个异常就是类所在的包不能是java.*的格式,直接修改包名即可解决。
Exception in thread "main" java.lang.SecurityException: Prohibited package name:


可以看到是ClassLoader抛出了异常,于是决定去ClassLoader类中去找找原因,直接搜索异常中的preDefineClass方法

    /* Determine protection domain, and check that:
        - not define java.* class,
        - signer of this class matches signers for the rest of the classes in
          package.
    */
    private ProtectionDomain preDefineClass(String name,
                                            ProtectionDomain pd)
    {
        if (!checkName(name))
            throw new NoClassDefFoundError("IllegalName: " + name);

        // Note:  Checking logic in java.lang.invoke.MemberName.checkForTypeAlias
        // relies on the fact that spoofing is impossible if a class has a name
        // of the form "java.*"
        if ((name != null) && name.startsWith("java.")) {
            throw new SecurityException
                ("Prohibited package name: " +
                 name.substring(0, name.lastIndexOf('.')));
        }
        if (pd == null) {
            pd = defaultDomain;
        }

        if (name != null) checkCerts(name, pd.getCodeSource());

        return pd;
    }

可以看到该方法对于类路径有检测,不能是java开头,即所在的包不能是java.*。