public class CryptoClassLoader extends ClassLoader {
private int key;
public CryptoClassLoader(int k){
this.key = k;
}
protected Class findClass(String name) throws ClassNotFoundException {
byte[] classBytes = null;
try{
classBytes = loadClassBytes(name);
}catch(IOException e){
throw new ClassNotFoundException(name);
}
Class cl = defineClass(name,classBytes,0,classBytes.length);
if(cl==null)
throw new ClassNotFoundException(name);
return cl;
}
private byte[] loadClassBytes(String name)throws IOException{
String cname = name.replace(".","/")+".caesar";
FileInputStream in = null;
in = new FileInputStream(cname);
try{
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int ch;
while((ch=in.read())!=-1){
byte b = (byte)(ch-key);
buffer.write(b);
}
in.close();
return buffer.toByteArray();
}finally{
in.close();
}
}
}
protected Class findClass(String name)
类加载器应该覆盖该方法,以查找类的字节码,并通过调用defineClass方法将字节码传给虚拟机.
Class defineClass(String name,byte[] data,int offset,int length)
参数 name 类名使用.作为包名分隔符
data 用于存放该类字节码的数组
offset 数组中字节码的起始位置
length 数组中字节码的长度