16_3.jdk动态代理与aop

本文深入探讨了JDK动态代理的实现原理,并通过具体示例展示了如何使用动态代理来实现面向切面编程(AOP)。文章首先定义了一个Subject接口及其实现类RealSubject,随后利用动态代理创建了该接口的代理实例,并调用了其say方法。此外,还介绍了如何将通用方法的执行逻辑嵌入到目标方法调用前后,进一步体现了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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值