16_3.jdk动态代理与aop

jdk动态代理:

public interface Subject {
    void say(String name,int age);
}
public class RealSubject implements Subject {
    @Override
    public void say(String name, int age) {
        System.out.println("say...");
    }
}

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

public class MyInvocation implements InvocationHandler {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        RealSubject instance = new RealSubject();
        MyInvocation myInvocation = new MyInvocation(instance);

        Subject o = (Subject) Proxy.newProxyInstance(instance.getClass().getClassLoader(), instance.getClass().getInterfaces(), myInvocation);
        o.say("p",12);

    }
    private Subject target;
    public MyInvocation(Subject subject) throws IllegalAccessException, InstantiationException {
        target = subject;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object invoke = method.invoke(target, args);
        return invoke;
    }
}

aop


public interface Dog {
    void info();
    void run();
}

public class HuntingDog implements Dog {
    @Override
    public void info() {
        System.out.println("我是一只猎狗");
    }
    @Override
    public void run() {
        System.out.println("我奔跑迅速");
    }
}

public class DogUtil {
    public void method1(){
        System.out.println("=====模拟通用方法一=====");
    }
    public void method2(){
        System.out.println("=====模拟通用方法二=====");
    }
}


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

public class MyInvocationHandler implements InvocationHandler {
    private Object target;
    public void setTarget(Object target){
        this.target = target;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        DogUtil dogUtil = new DogUtil();
        dogUtil.method1();
        Object res = method.invoke(target, args);
        dogUtil.method2();
        return res;
    }
}

import java.lang.reflect.Proxy;

public class MyProxyFactory {
    public static Object getProxy(Object target){
        MyInvocationHandler handler = new MyInvocationHandler();
        handler.setTarget(target);
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),handler);
    }
}
原文地址:https://www.cnblogs.com/fly-book/p/11549817.html