我们自己编写的Java类默认情况下都由系统类加载器加载。系统类加载器也是ClassLoader的子类,也是通过调用ClassLoader.loadClass(name)方法来加载类,而扩展ClassLoader类的一般做法就是重写findClass(name)方法,然后调用defineClass(String name, byte[] b, int off, int len)返回。所以我们可以直接看ClassLoader的defineClass(String name, byte[] b, int off, int len)方法。
defineClass(String name, byte[] b, int off, int len)方法:
protected final Class<?> defineClass(String name, byte[] b, int off, int len)
throws ClassFormatError
{
return defineClass(name, b, off, len, null);
}
defineClass(String name, byte[] b, int off, int len, ProtectionDomain protectionDomain)方法:
protected final Class<?> defineClass(String name, byte[] b, int off, int len,
ProtectionDomain protectionDomain)
throws ClassFormatError
{
check();
protectionDomain = preDefineClass(name, protectionDomain);
Class c = null;
String source = defineClassSourceLocation(protectionDomain);
try {
c = defineClass1(name, b, off, len, protectionDomain, source);
} catch (ClassFormatError cfe) {
c = defineTransformedClass(name, b, off, len, protectionDomain, cfe, source);
}
postDefineClass(c, protectionDomain);
return c;
}
preDefineClass(String name,ProtectionDomain protectionDomain)方法有如下一段代码:
if ((name != null) && name.startsWith("java.")) {
throw new SecurityException("Prohibited package name: " +
name.substring(0, name.lastIndexOf('.')));
}
如果类名不为空,并且以java.开头,就抛出异常!
当然,检测包名不只这么简单,正式加载字节码文件的时候还会对包名进行检测。