public static void main(String[] args) {
System.out.println("AppClassLoader : "+LoaderTest1.class.getClassLoader());
System.out.println("用户自定义的jar包 放在ext目录下加载的jar : "+TestExtLoader.class.getClassLoader().getClass().getName());
System.out.println("由jvm初始加载器加载的jar 包 BootStrap: "+String.class.getClassLoader());
}。
ClassLoader loader = ClassLoaderTest.class.getClassLoader();
//打印出当前的类装载器,及该类装载器的各级父类装载器
while(loader != null)
{
System.out.println(loader.getClass().getName());
loader = loader.getParent();
}
BootStrap ----- JRE/lib/rt.jar 顶层加载器
ExtClassLoade--- JRE/lib/ext/*.jarpackage classLoader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
public class MyClassLoader extends ClassLoader{
private String dir = null;
public MyClassLoader(String dir) throws RuntimeException{
if(new File(dir).isDirectory()){
this.dir = dir;
}else{
throw new RuntimeException("The dir : '"+dir+"' is not find !");
}
}
public static void main(String[] args) throws Exception {
MyClassLoader m = new MyClassLoader("idcastlib");
Date d = (Date)m.loadClass("TestLoader").newInstance();
System.out.println(d.toString());
}
@SuppressWarnings("deprecation")
@Override
protected Class> findClass(String name) throws ClassNotFoundException {
String filePath = name+".class";
File f = new File( dir , filePath);
System.out.println(f.getPath());
FileInputStream fi = null;
ByteArrayOutputStream bo = null;
try {
fi = new FileInputStream(f);
bo = new ByteArrayOutputStream();
encrypt(fi,bo);
byte[] bs = bo.toByteArray();
System.out.println(bs.length);
return this.defineClass( bs, 0, bs.length);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
throw new ClassNotFoundException(name + " not find ");
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("io error");
} finally{
try {
if(fi != null)fi.close();
if(bo!=null)bo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return super.findClass(name);
}
/**
* 对class文件进行加密处理
* @param is
* @param out
* @throws IOException
*/
private void encrypt(InputStream is, OutputStream out) throws IOException {
int i = -1;
while((i = is.read())!= -1){
out.write(i^0xff);
}
}
}
//类加载器不能加载这种非public的类
/*
Exception in thread "main" java.lang.IllegalAccessException: Class MyClassLoader
can not access a member of class MyTest with modifiers ""
*/
/*
class MyTest
{
public void test()
{
System.out.println("hello,www.it315.org");
}
}
结论: 父级类加载器加载的类无法引用只能被子级类加载器加载的类。