类加载器
BootStrap(jre/lib/rt.jar ) 、 ExtClassLoader(jre/lib/ext/*.jar) 、 AppClassloader(classPath指定的所有jar包及其class类)
、
虚拟机默认自动加载BootStrap 然后按照类加载继承树一次往下加载每个加载器。 类加载器的原理是委托机制,一次往上类推,如果上面成功加载,则下面的加载器就不在加载。如果从上往下都没有加载成功。自己加载也没有成功,则返回classNoFound异常
自定义类加载器:
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MyLoader extends ClassLoader {
public static void main(String args[]) throws IOException {
ClassLoader loader = MyLoader.class.getClassLoader();
while (loader != null) {
System.out.println(loader);
loader = loader.getParent();
}
String[] ss ={new String("E:\\javaweb\\enhanceHigh\\bin\\Test.class"),new String("class")};
setClass(ss);
}
private static void setClass(String[] args) throws FileNotFoundException,
IOException {
String srcPath = args[0];
String destDir = args[1];
FileInputStream in = new FileInputStream(srcPath);
String destPath = destDir + "\\"
+ srcPath.substring(srcPath.lastIndexOf('\\') + 1);
FileOutputStream out = new FileOutputStream(destPath);
cypher(in, out);
in.close();
out.close();
}
@SuppressWarnings("deprecation")
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
// TODO Auto-generated method stub
String classFileName=classDir+"\\"+name+".class";
try {
FileInputStream fis=new FileInputStream(classFileName);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
cypher(fis, bos);
byte[] by=bos.toByteArray();
return defineClass(by, 0, by.length);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.findClass(name);
}
/**
* 数据加密类
* @param in
* @param out
* @throws IOException
*/
public static void cypher(InputStream in, OutputStream out)
throws IOException {
int b = -1;
while ((b = in.read()) != -1) {
out.write(b ^ 0xff);
}
}
private String classDir;
public MyLoader(String classDir){
this.classDir=classDir;
}
}
注意:自己的类加载时,一定要确保父类加载器中没有此类,否则父类加载了,子类就加在不上了。这里是模板模式 !