import java.util.ResourceBundle;
public class Test {
public static void main(String args[]) {
ResourceBundle.getBundle("openfire_i18n");
}
}
先看上述代码运行结果,如果没有做任何额外设置,就会报:
Exception in thread "main" java.util.MissingResourceException: Can't find bundle for base name openfire_i18n, locale zh_CN
at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1427)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1250)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:705)
at Test.main(Test.java:6)
表示找不到资源,其实是没有设定好寻找资源的路径,也就是ClassPath,那为什么会是ClassPath呢?
我们知道,这里getBundle相当于
getBundle(baseName, Locale.getDefault(), this.getClass().getClassLoader());
它是有利用默认的Locale和ClassLoader的,而这个ClassLoader恰恰有与ClassPath绑定,看下文:
You can certainly set any system properties you want at any point of time. The question is, will it have any effect?
In the case of classpath, the answer is NO. The system class loader is initialized at a very early point in the
startup sequence. It copies the classpath into its own data structures, and the classpath property is not read again. Changing it affect nothing in the system.
但现在问题来了,ClassLoader的doc解释中我并没有找到ClassPath相关的,看Class类:
public ClassLoader getClassLoader() {
ClassLoader cl = getClassLoader0();
if (cl == null)
return null;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
ClassLoader ccl = ClassLoader.getCallerClassLoader();
if (ccl != null && ccl != cl && !cl.isAncestor(ccl)) {
sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
}
}
return cl;
}
可见,应该是在native方法getClassLoader0中实现的,将ClassPath信息纳入搜寻动作中