先看一个例子
package com.cqs.learning.jvm;
import jdk.nashorn.tools.Shell;
import java.io.IOException;
import java.io.InputStream;
/**
* @author lixiaowen
* @create 19-2-28
*/
public class ClassLoaderDemo {
public static void main(String[] args) {
// bootstrap class loader example &&
System.out.println(Object.class + " classloader: "+ Object.class.getClassLoader());
//ext class loader example
//System.out.println(System.getProperty("java.ext.dirs"));
System.out.println(Shell.class + " classloader: " + Shell.class.getClassLoader());
//App class loader example
System.out.println(ClassLoaderDemo.class + " classloader: " + ClassLoaderDemo.class.getClassLoader());
// self define class loader example
SelfDefineClassLoader selfDefineClassLoader = new SelfDefineClassLoader();
try {
//指定自定义加载器
Class<?> aClass = selfDefineClassLoader.loadClass("com.cqs.learning.jvm.ClassLoaderDemo");
Object o = aClass.newInstance();
System.out.println(o.getClass() +"\t classloader: " + o.getClass().getClassLoader());
//System.out.println(o instanceof com.cqs.learning.jvm.ClassLoaderDemo);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
static class SelfDefineClassLoader extends ClassLoader{
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
String fileName = name.substring(name.lastIndexOf(".")+1) + ".class";
InputStream is = getClass().getResourceAsStream(fileName);
if (is == null){
return super.loadClass(name);
}
try {
byte[] bytes = new byte[is.available()];
is.read(bytes);
return defineClass(name,bytes,0, bytes.length);
} catch (IOException e) {
throw new RuntimeException();
}
}
}
}