今天发下一个问题,自定义的包不能以java.开头,虽然编辑时很正常import,然后在编译的时候就找不到类了,为什么呢?
要是因为它是java开头,与library里面默认的一些包有冲突,那以com.开头的包怎么不与冲突呢

解决方案 »

  1.   

    Java 的 ClassLoader 人为地进行了限制,不允许开发人员自定义 java 开头的包。
      

  2.   

    01 /* Determine protection domain, and check that:
    02    - not define java.* class,
    03    - signer of this class matches signers for the rest of the classes in package.
    04  */
    05 private ProtectionDomain preDefineClass(String name, ProtectionDomain protectionDomain) {
    06     if (!checkName(name))
    07         throw new NoClassDefFoundError("IllegalName: " + name);
    08 
    09     if ((name != null) && name.startsWith("java.")) {
    10         throw new SecurityException("Prohibited package name: " + name.substring(0, name.lastIndexOf('.')));
    11     }
    12     if (protectionDomain == null) {
    13         protectionDomain = getDefaultDomain();
    14     }
    15     if (name != null)
    16         checkCerts(name, protectionDomain.getCodeSource());
    17     return protectionDomain;
    18 }上面这段代码是 java.lang.ClassLoader 中 preDefineClass 方法的代码,注意一下第 9 行。