Java 类加载器、动态代理类等(系列上)

Java 类加载器、动态代理类等(系列下)

 

@version 1.0 2011.01.12


9,类加载器

→类加载器的委托机制

 

→自定义类加载器编写原理

   扩展1:  http://blog.****.net/miyao16/archive/2009/11/30/4909374.aspx

   扩展2:  http://www.iteye.com/topic/136427

 

    

→class文件转换为字节码 defineClass()

→class文件加密

----------------------------------

//自定义加密算法
private static void cypher(InputStream ips ,OutputStream ops) throws Exception{
      int b = -1;
      while((b=ips.read())!=-1){
            ops.write(b ^ 0xff);
      }
}

 

//自定义类加载器 加载加密后的class文件(解密)
public MyClassLoader(){

}
public MyClassLoader(String classDir){
      this.classDir = classDir;
}
private String classDir;
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
      // TODO Auto-generated method stub
      String classFileName = classDir + "\\"  + 
      name.substring(name.lastIndexOf('.')+1) + ".class";
      try {
           FileInputStream fis = new FileInputStream(classFileName);
            ByteArrayOutputStream  bos =  new ByteArrayOutputStream();
            cypher(fis,bos); 
            fis.close();
            System.out.println("aaa");
            byte[] bytes = bos.toByteArray();
            return defineClass(bytes, 0, bytes.length);
      } catch (Exception e) {
            e.printStackTrace();
      }
return null;
}

 

//测试用例
public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    String srcPath = args[0];
    String destDir = args[1];
    FileInputStream fis = new FileInputStream(srcPath);
    String destFileName = srcPath.substring( srcPath.lastIndexOf('\\')+1);
    String destPath = destDir + "\\" + destFileName;
    FileOutputStream fos = new FileOutputStream(destPath);
    cypher(fis,fos);
    fis.close();
    fos.close();
}
 

 


10,动态类

→动态代理类设计原理与方法

 

→可配置AOP框架(spring)分析