java程序运行及类加载流程图示
自定义类加载器打破双亲委派
package com.tao.jvm;
import java.io.FileInputStream;
import java.lang.reflect.Method;
public class MyClassLoader extends ClassLoader {
private String classPath;
public MyClassLoader(String classPath) {
this.classPath = classPath;
}
private byte[] loadByte(String name) throws Exception {
name = name.replaceAll("\\.", "/");
FileInputStream inputStream = new FileInputStream(classPath+"/"+name+".class");
int len = inputStream.available();
byte[] data = new byte[len];
inputStream.read(data);
inputStream.close();
return data;
}
/**
* 根据加载的名称,从指定路径加载资源
* **/
//@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
try {
byte[] data = loadByte(name);
return defineClass(name, data, 0, data.length);
}catch (Exception e) {
throw new ClassNotFoundException();
}
}
/**
* 打破双亲委派机制
* **/
//@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
// First, check if the class has already been loaded
Class<?> c = findLoadedClass(name);
if (c == null) {
long t0 = System.nanoTime();
// 从父类加载逻辑注释
// try {
// if (parent != null) {
// 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 (name.startsWith("com.tao.jvm")) {
// 只加载自己定义的
c = findClass(name);
}else {
// 其他还是由上层加载器加载
c = this.getParent().loadClass(name);
}
if (c == null) {
// If still not found, then invoke findClass in order
// to find the class.
long t1 = System.nanoTime();
// this is the defining class loader; record the stats
sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
sun.misc.PerfCounter.getFindClasses().increment();
}
}
if (resolve) {
resolveClass(c);
}
return c;
}
}
public static void main(String[] args) throws Exception {
MyClassLoader classLoader = new MyClassLoader("E:\\jvm_test");
Class cls = classLoader.loadClass("com.tao.jvm.User");
Object obj = cls.newInstance();
Method method = cls.getDeclaredMethod("print", null);
method.invoke(obj, null);
System.out.println(cls.getClassLoader().getClass().getName());
}
}
输出结果
user1 执行方法
com.tao.jvm.MyClassLoader