黑马程序员--加强之ClassLoader

-------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培训 、期待与您交流!     ----------  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值