java反射系列八之AOP

package AOP;

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

interface Human{
    void info();
    void fly();
}

class SuperMan implements Human{
    @Override
    public void info() {
        System.out.println("我是超人");
    }
    public void fly() {
        System.out.println("I believe that I can fly!");
    }
}

class HumanUtil{
    public void method1() {
        System.out.println("=====方法一======");
    }
    public void method2() {
        System.out.println("=====方法二======");
    }
}

class MyInvocationHandler implements InvocationHandler{
    //被代理对象的声明
    Object obj;
    
    public void setObject(Object obj) {
        this.obj=obj;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        HumanUtil h = new HumanUtil();
        h.method1();
        
        Object returnValue = method.invoke(obj, args);
        
        h.method2();
        return returnValue;
    }
    
}
//动态的创建一个代理类的对象
class MyProxy{
    public static Object getProxyInstance(Object obj) {
        MyInvocationHandler hander = new MyInvocationHandler();
        hander.setObject(obj);
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
                obj.getClass().getInterfaces(), hander);
    }
}
public class TestAop {
    public static void main(String[] args) {
        //创建一个被代理类的对象
        SuperMan man = new SuperMan();
        //返回一个代理类的对象
        Object obj = MyProxy.getProxyInstance(man);
        Human hu = (Human)obj;
        hu.info();
        System.out.println();
        hu.fly();
    }
}

原文地址:https://www.cnblogs.com/zjm1999/p/10345032.html