1. 加載完就不加載的寫法
1.1是不是可以參考雙親委派機制
1.2那就分析一下ClassLoader源碼吧
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
// First, check if the class has already been loaded
Class<?> c = findLoadedClass(name);
if (c == null) {
try {
if (parent != null) {
// 注釋1 parent 為父加載器,可以自定義一個classLoader 依次打印出所有父類
c = parent.loadClass(name, false);
} else {
c = findBootstrapClassOrNull(name);
}
} catch (ClassNotFoundException e) {
// ClassNotFoundException thrown if class not found
// from the non-null parent class loader
}
if (c == null) {
// If still not found, then invoke findClass in order
// to find the class.
c = findClass(name);
}
}
return c;
}
注釋1 :默認構(gòu)造函數(shù)的classLoader為 PathClassLoader
parent 為父加載器,可以自定義一個classLoader 依次打印出所有parent
private static ClassLoader createSystemClassLoader() {
String classPath = System.getProperty("java.class.path", ".");
String librarySearchPath = System.getProperty("java.library.path", "");
// String[] paths = classPath.split(":");
// URL[] urls = new URL[paths.length];
// for (int i = 0; i < paths.length; i++) {
// try {
// urls[i] = new URL("file://" + paths[i]);
// }
// catch (Exception ex) {
// ex.printStackTrace();
// }
// }
//
// return new java.net.URLClassLoader(urls, null);
// TODO Make this a java.net.URLClassLoader once we have those?
return new PathClassLoader(classPath, librarySearchPath, BootClassLoader.getInstance());
}
2.1做法比較簡單但是有幾個要注意的地方
- 盡量不要在方法中直接return
- 注意函數(shù)單一性原則
總結(jié)
東西很簡單,就是修改bug的時候突然想到的,大家遇到不知道怎么實現(xiàn)比較合理的時候其實可以參考源碼,既可以了解源碼是怎么實現(xiàn)的(說不定面試的時候用的上呢),也可以用到實踐中。雖然簡單但是也有意義!