黑马程序员--学习--类加载器和代理

来源:互联网 发布:手机怎么登陆淘宝店铺 编辑:程序博客网 时间:2024/04/29 02:32

---------------------- android培训java培训、期待与您交流! ----------------------

 类加载器
系统默认的三个主要类加载器
BootStrap,ExtClassLoader,AppClassLoader
编写自己的类加载器

知识讲解
1.自定义的类加载器必须继承ClassLoader
2.loadClass方法与findClass方法
3.defineClass方法

步骤
1.编写一个对文件内容进行简单加密的程序
2.编写一个自己的类加载器,可实现对加密过的类进行装载和解密
3.编写一个程序调用类加载器加载类,在源程序中不能用该类名定义引用变量,因为编译器无法识别这个类
程序中可以除了使用ClassLoader.load方法之外,还可以使用设置线程的上下文类加载器或者系统类加载器,
然后再使用Class.forName

 

 

public class  MyClassLoader
{
 public static void main(String[] args) throws Exception
 {
  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();

 }
 public static void sypher(InputStream ips,OutputStream ops)throws Exception{                                   //加密方法
  int b = -1;
  while((b=ips.read()!=-1)){
   ops.write(b ^ 0xff);
  }
 }
 private String classDir;
 @Override
 protected Class<?>findClass(String name)throws ClassNotFoundException{
  String classFileName = classDir +"
\\"+name.substring(name.lastIndextOf('.'+1))+".class";
  try{

   FileInputStream fis = new FileInputStream(classFileName);
   ByteArrayOutputStream bos = new ByteArrayOutputStream();
   cypher(fis,bos);                                                        //解密
   fis.close();
   byte[] bytes= bos.toByteArray();
   return defineClass(bytes,0,bytes.length);
  }catch(Exception e){
   e.printStackTrace();
  }
  return null;
 }
 public MyClassLoader(){
 
 }
 public MyClassLoader(){
  this.classDir = classDir;
 }
}

 

public class  ClassLoader
{
 public static void main(String[] args) throw Exception
 {
  Class clazz = new MyClassLoader("itcastlib").loadClass("cn.itcast.day.ClassLoaderAttachment");
  Date d1 = (Date)clazz.newInstance();
  System.out.println(d1);
 }
}


import java.util.Date;
public class ClassLoaderAttachment extends Date
{
 public String toString(){
  return "hello";
 }
}

 


用Proxy.newInstance方法直接创建出代理对象
public class Proxy
{
 public static void main(String[] args){
 
  Collection proxy1 = (Collection)Proxy.newProxyInstance(
  Collection.class.getClassLoader(),
  new InvocationHandler(){
   public Object invoke(Object proxy,Method method,Object[] args)throws Throwable{
    ArrayList target = new ArrayList();
    Object retVal =  method.invoke(target,args);
    return retVal;
   }
  }
  );
 proxy1.add("ddsa");
 proxy1.add("22a");
 proxy1.add("3232"); 
 System.out.println(proxy1.size()); 
 }


}

 

---------------------- android培训java培训、期待与您交流! ----------------------

原创粉丝点击