代理

2019-03-27  本文已影响0人  白纸糊
package cn.alittle.Main.Refelct;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import org.omg.CORBA.SystemException;
import org.omg.CORBA.portable.InputStream;
import org.omg.CORBA.portable.InvokeHandler;
import org.omg.CORBA.portable.OutputStream;
import org.omg.CORBA.portable.ResponseHandler;

public class MyProxy implements InvocationHandler {

    private Object target;

    public MyProxy(Object target) {
        super();
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method methond, Object[] args) throws Throwable {
        System.out.println("校验");
        Object invoke = methond.invoke(target, args);
        System.out.println("记录");
        return invoke;
    }
   
}

package cn.alittle.Main.Refelct;

import java.lang.reflect.Proxy;

public class MyProxyFactory<T> {
        
        // 为指定target生成动态代理对象
    public  T getProxy(Object target) throws Exception {
        // 创建一个MyInvokationHandler对象
        MyProxy handler = new MyProxy(target);
        // 为MyInvokationHandler设置target对象
//      handler.setTarget(target);
        // 创建、并返回一个动态代理对象
        return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler);
    }

}


package cn.alittle.Main.Refelct;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.lang.reflect.Proxy;
import java.util.ArrayList;

import org.junit.Test;

public class proxy {
@Test
    public  void main() throws Exception {
    Student student = new Student();
        MyProxy myProxy = new MyProxy(student);
        //类的加载器 类的接口 类的代理
        School proxy = (School)Proxy.newProxyInstance(student.getClass().getClassLoader(), new Class[] {School.class},
                myProxy);
        proxy.eat();
        
        MyProxyFactory<School> myProxyFactory = new MyProxyFactory<School>();
         School proxy2 = myProxyFactory.getProxy(student);
         proxy2.eat();
//  try (BufferedReader bufferedReader = new BufferedReader(new FileReader(""))  ){
//      
//  }
  }
}
上一篇下一篇

猜你喜欢

热点阅读