图解说明如下:
1.双亲委派机制是可以打破的
package com.tuling.jvm;
import java.io.FileInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Description:
* Author: taimi 37310
* Version: 1.0
* Create Date Time: 2022/4/21 5:11.
* Update Date Time:
*
* @see
*/
public class MyClassLoaderTest {
static 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 fis = new FileInputStream(classPath + "/" + name + ".class");
int len = fis.available();
byte[] data = new byte[len];
fis.read(data);
fis.close();
return data;
}
protected Class<?> findClass(final String name)
throws ClassNotFoundException {
final Class<?> result;
try {
byte[] data = loadByte(name);
//直接返回验证信息,不去查找 Resource res = ucp.getResource(path, false);
//少一步从父类加载器中查找类的过程
//加载后,验证,准备,解析,初始化,底层是c++实现
return defineClass(name,data,0,data.length);
} catch (Exception e) {
e.printStackTrace();
throw new ClassNotFoundException();
}
}
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 (c == null) {
// If still not found, then invoke findClass in order
// to find the class.
long t1 = System.nanoTime();
//如果不是自定义的ClassLoader走双亲委派机制
if(!name.startsWith("com.tuling.jvm")){
c = this.getParent().loadClass(name);
}else {
//否则直接加载类信息到jvm
c = findClass(name);
}
// this is the defining class loader; record the stats
sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
sun.misc.PerfCounter.getFindClasses().increment();
}
if (resolve) {
resolveClass(c);
}
return c;
}
}
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
MyClassLoader classLoader = new MyClassLoader("D:/test");
Class<?> clazz = classLoader.loadClass("com.tuling.jvm.User1");
Object obj = clazz.newInstance();
Method method = clazz.getDeclaredMethod("sout", null);
method.invoke(obj, null);
System.out.println(clazz.getClassLoader().getClass().getName());
}
}
}
2.如何打破,原理是什么
//如果不是自定义的ClassLoader走双亲委派机制
if(!name.startsWith("com.tuling.jvm")){
c = this.getParent().loadClass(name);
}else {
//否则直接加载类信息到jvm
c = findClass(name);
}
byte[] data = loadByte(name);
//直接返回验证信息,不去查找 Resource res = ucp.getResource(path, false);
//少一步从父类加载器中查找类的过程
//加载后,验证,准备,解析,初始化,底层是c++实现
return defineClass(name,data,0,data.length);