-------android培训、java培训、期待与您交流! ----------
package cn.itcast.day2;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
//1. 先将生成的ClassLoaderAttachment.class 文件加密,存放到my_class_patch文件夹中
//2.自定义my_class_loader, 继承 ClassLoader,实现findClass方法
public class MyClassLoader extends ClassLoader
{
private String classFileDir = "my_class_path/";
private static int key = 100;
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException
{
//load class file data
byte[] fileBytes = null;//类文件的字节数组
try
{
InputStream in = new FileInputStream(classFileDir+name);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
cyper(in, bos);
in.close();
fileBytes = bos.toByteArray();
} catch (Exception e)
{
e.printStackTrace();
}
//返回要加载的类
return defineClass(fileBytes, 0, fileBytes.length);
//return super.findClass(name);
}
private static void cyper(InputStream in, OutputStream out)
throws IOException
{
int len = 0;
byte[] buf = new byte[1024];
while(-1 != (len=in.read(buf)))
{
for(int i=0; i<len; i++)
buf[i] ^= key;
out.write(buf,0,len);
out.flush();
}
}
private static void cyper2(InputStream in, OutputStream out)
throws IOException
{
int b = -1;
while((b=in.read())!=-1){
out.write(b ^ 0xff);
out.flush();
}
}
public static void main(String[] args) throws IOException
{
String srcClassDir = "cn/itcast/day2/";
String srcClassFile = "ClassLoaderAttachment.class";
String srcClassPath = srcClassDir + srcClassFile;
InputStream in = null;
OutputStream out = null;
try
{
in =
ClassLoader.getSystemClassLoader().getResourceAsStream(srcClassPath);
}
finally
{
in.close();
}
try
{
out = new FileOutputStream("my_class_path/"+srcClassFile); //hard code !xx 第二次加载会出现问题,它会清空原文件
cyper(in,out);
}
finally
{
out.close();
}
//将源文件删除
File f = new File("bin/"+srcClassPath);
System.out.println(f.getAbsolutePath());
if(f.delete())
System.out.println("source file deleted successfully!");
else
System.out.println("source file deleted failly");
}
}
-------
android培训
、
java培训
、期待与您交流! ----------