public ClassLoaderLK(String path) {
this.path = path;
}
//实现了双亲委派
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
// return super.loadClass(name);
Class<?> cls = findLoadedClass(name);//主要是检查类是否有加载过
if (cls == null) {
// cls = getSystemClassLoader().loadClass(name); (2)// SystemClassLoader 会从classpath下加载
// if (cls == null) {(2)
// 默认情况下, 当前cl的parent是 SystemClassLoader,
// 而当前cl的parent的parent 才是ExtClassLoader
ClassLoader parent1 = getParent();
ClassLoader parent2 = parent1.getParent();
// System.out.println("Classloader is : " + parent2);
//使用父classload 就是appClassLoad
try {
System.out.println("try to use APPClassLoader to load class : " + name);
cls = parent1.loadClass(name);
} catch (ClassNotFoundException e) {
System.out.println("APPClassLoader.loadClass :" + name + " Failed");
}
//这里是使用extClassLoader加载
/* try {
System.out.println("try to use ExtClassLoader to load class : " + name);
cls = parent2.loadClass(name);
} catch (ClassNotFoundException e) {
System.out.println("ExtClassLoader.loadClass :" + name + " Failed");
}*/
// }(2)
if (cls == null) {
System.out.println("try to ClassLoaderLK load class : " + name);
cls = findClass(name);
if (cls == null) {
System.out.println("ClassLoaderLK.loadClass :" + name + " Failed");
} else {
System.out.println("ClassLoaderLK.loadClass :" + name + " Successful");
}
} else {
System.out.println("ExtClassLoader.loadClass :" + name + " Successful");
}
}
return cls;
}
//没有实现双亲委派
@Override
@SuppressWarnings("rawtypes")
public Class<?> findClass(String name) throws ClassNotFoundException {
// return super.findClass(name);
System.out.println( "try findClass " + name);
InputStream is = null;
Class class1 = null;
try {
String classPath = name.replace(".", "\\") + ".class";
// String[] fqnArr = name.split("\\."); // split("."); 是不行的, 必须split("\\.")
// if (fqnArr == null || fqnArr.length == 0) {
// System.out.println("ClassLoaderLK.findClass()");
// fqnArr = name.split("\\.");
// } else {
// System.out.println( name + fqnArr.length);
// }
String classFile = path + classPath;
byte[] data = getClassFileBytes(classFile );
class1 = defineClass(name, data, 0, data.length);
if (class1 == null) {
System.out.println("ClassLoaderLK.findClass() ERR ");
throw new ClassFormatError();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return class1;
}
Java 类加载的一些理解(4)
内容版权声明:除非注明,否则皆为本站原创文章。
转载注明出处:https://www.heiqu.com/0f1b3fc2d9109fefd22c10b82f52f3f5.html