动态代理(基础)

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

interface TargetInterface{
    void doSomething();
}
class TargetObject implements TargetInterface{
    @Override
    public void doSomething() {
        System.out.println("TargetObject do something");
    }
}
//代理对象的思路:
//1.因为需要增强方法,所以需要处理原实例对象的方法
// (通过InvocationHandler接口实现组合原实例对象和对原实例对象的方法进行增强)
//2.因为是代理,所以需要代理对象(通过Proxy对象实现)
class InvocationHandlerImpl implements InvocationHandler {
    private Object target;
    public InvocationHandlerImpl(Object target) {//组合原实例对象
        this.target = target;
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {//对原实例对象的方法进行增强
        System.out.println("Do something before");
        Object result = method.invoke(target, args);
        System.out.println("Do something after");
        return result;
    }
}

public class dealProcess{
    public static void main(String[] args) {
        //目标类
        TargetObject targetObject=new TargetObject();
        TargetInterface proxyObject=(TargetInterface)Proxy.newProxyInstance(targetObject.getClass().getClassLoader(), targetObject.getClass().getInterfaces(), new InvocationHandlerImpl(targetObject))   ;
        
        //Proxy.newProxyInstance源码:
        //final Class[] intfs = interfaces.clone();复制接口的信息使其不可变
        //Class cl = getProxyClass0(loader, intfs);生成带intfs的class类对象信息
        //final Constructor cons = cl.getConstructor({ InvocationHandler.class });找到以处理类为构造器的构造器
        //cons.setAccessible(true)如果构造器不可见设置可见(public)
        //return cons.newInstance(new Object[]{h});通过向带处理类的构造器传入处理类实例反射实例化
        proxyObject.doSomething();
        //proxyObject代理类组合了处理对象,参考静态代理,proxyObject.doSomething()方法里会去调用处理类的invoke(Object proxy, Method method, Object[] args)方法,args为调用方法参数

    }
}

你可能感兴趣的:(java,java,设计模式,反射,aop,proxy)