如果想看一下簡單的類加載器怎麼自定義,可以跳轉簡單自定義類加載器
自定義加密解密類加載器
測試簡單的class文件加密解密(取反操作)。取反加密只是一個簡單示例。
加密工具類(字節按位取反)
package com.feng.ClassTest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 加密工具類
* @author feng
*
*/
public class EncrpUtil {
public static void main(String[] args) {
// TODO Auto-generated method stub
encrpt("E:\\myjava\\HelloWorld.class", "E:\\myjava\\temp\\HelloWorld.class");
}
public static void encrpt(String src, String dest) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(src);
fos = new FileOutputStream(dest);
int temp = -1;
while((temp = fis.read()) != -1) {
fos.write(temp^0xff); //異或,每個字節按位取反
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(fis != null) {
fis.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(fos != null) {
fos.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
解密類加載器
package com.feng.ClassTest;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* 加載文件系統加密後的class字節碼的類加載器
* @author feng
*
*/
public class DecreptClassLoader extends ClassLoader {
private String rootDir;
public DecreptClassLoader(String rootDir) {
this.rootDir = rootDir;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
Class<?> c = null;
byte[] classData = getClassData(name); // 自定義方法獲取類字節碼
if(classData == null) {
throw new ClassNotFoundException(); // 如果字節數組爲空,拋出異常
} else {
try {
c = defineClass(name, classData, 0, classData.length);
} catch (ClassFormatError e){ // 加載錯誤
e.printStackTrace();
c = null;
}
}
return c;
}
private byte[] getClassData(String classname) {
// 拼出類class文件地址
String path = rootDir + "/" + classname.replace('.', '/') + ".class";
InputStream fis = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
fis = new FileInputStream(path);
int temp = -1;
while((temp = fis.read()) != -1) {
baos.write(temp^0xff); //異或,每個字節按位取反
}
return baos.toByteArray();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} finally {
try {
if(fis != null) {
fis.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(baos != null) {
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
測試自定義解密類加載器
package com.feng.ClassTest;
public class Demo04 {
public static void main(String[] args) throws ClassNotFoundException {
//加密後的class文件,正常的類加載器 無法加載,會報FormatError錯誤
//FileSystemClassLoader loader = new FileSystemClassLoader("E:\\myjava\\temp");
//Class<?> c = loader.findClass("HelloWorld");
//System.out.println(c);
// 使用解密類加載器
DecreptClassLoader loader = new DecreptClassLoader("E:\\myjava\\temp");
Class<?> c = loader.loadClass("HelloWorld");
System.out.println(c);
}
}