Java应用类的包名为什么不能以java.开头?

我们自己编写的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.开头,就抛出异常!

当然,检测包名不只这么简单,正式加载字节码文件的时候还会对包名进行检测。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值