AOP实现过滤JoinPoint,所用到的反射原理代码

/*

 * Licensed to the Apache Software Foundation (ASF) under one or more

 * contributor license agreements. See the NOTICE file distributed with

 * this work for additional information regarding copyright ownership.

 * The ASF licenses this file to You under the Apache License, Version 2.0

 * (the "License"); you may not use this file except in compliance with

 * the License. You may obtain a copy of the License at

 *

 * http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */


import java.lang.reflect.InvocationHandler;

import java.lang.reflect.Method;

import java.lang.reflect.Proxy;

/**
 * AOP 拦截器示例
 *
 * @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
 * @since
 */

public class AopInterceptorDemo {

    public static void main(String[] args) {

// 前置模式 + 后置模式

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        Object proxy = Proxy.newProxyInstance(classLoader, new Class[]{EchoService.class}, new InvocationHandler() {

            @Override

            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                if (EchoService.class.isAssignableFrom(method.getDeclaringClass())) {

// 前置拦截器

                    BeforeInterceptor beforeInterceptor = new BeforeInterceptor() {

                        @Override

                        public Object before(Object proxy, Method method, Object[] args) {

                            return System.currentTimeMillis();

                        }

                    };

                    Long startTime = 0L;

                    Long endTime = 0L;

                    Object result = null;

                    try {

// 前置拦截

                        startTime = (Long) beforeInterceptor.before(proxy, method, args);

                        EchoService echoService = new DefaultEchoService();

                        result = echoService.echo((String) args[0]); // 目标对象执行

// 方法执行后置拦截器

                        AfterReturnInterceptor afterReturnInterceptor = new AfterReturnInterceptor() {

                            @Override

                            public Object after(Object proxy, Method method, Object[] args, Object returnResult) {

                                return System.currentTimeMillis();

                            }

                        };

// 执行 after

                        endTime = (Long) afterReturnInterceptor.after(proxy, method, args, result);

                    } catch (Exception e) {

// 异常拦截器(处理方法执行后)

                        ExceptionInterceptor interceptor = (proxy1, method1, args1, throwable) -> {

                        };

                    } finally {

// finally 后置拦截器

                        FinallyInterceptor interceptor = new TimeFinallyInterceptor(startTime, endTime);

                        Long costTime = (Long) interceptor.finalize(proxy, method, args, result);

                        System.out.println("echo 方法执行的实现:" + costTime + " ms.");

                    }

                }

                return null;

            }

        });

        EchoService echoService = (EchoService) proxy;

        echoService.echo("Hello,World");

    }

}

class TimeFinallyInterceptor implements FinallyInterceptor {

    private final Long startTime;

    private final Long endTime;

    TimeFinallyInterceptor(Long startTime, Long endTime) {

        this.startTime = startTime;

        this.endTime = endTime;

    }

    @Override

    public Object finalize(Object proxy, Method method, Object[] args, Object returnResult) {

// 方法执行时间(毫秒)

        Long costTime = endTime - startTime;

        return costTime;

    }

}

//过滤原理,使用反射

 
public static void main(String[]args)throws ClassNotFoundException{

        String targetClassName="org.geekbang.thinking.in.spring.aop.overview.EchoService";

// 获取当前线程 ClassLoader

        ClassLoader classLoader=Thread.currentThread().getContextClassLoader();

// 获取目标类

        Class<?> targetClass=classLoader.loadClass(targetClassName);

// 方法定义:String echo(String message);

// Spring 反射工具类

        Method targetMethod=ReflectionUtils.findMethod(targetClass,"echo",String.class);

        System.out.println(targetMethod);

// 查找方法 throws 类型为 NullPointerException

        ReflectionUtils.doWithMethods(targetClass,new ReflectionUtils.MethodCallback(){

@Override

public void doWith(Method method)throws IllegalArgumentException,IllegalAccessException{

        System.out.println("仅抛出 NullPointerException 方法为:"+method);

        }

        },new ReflectionUtils.MethodFilter(){

@Override

public boolean matches(Method method){

        Class[]parameterTypes=method.getParameterTypes();

        Class[]exceptionTypes=method.getExceptionTypes();

        return parameterTypes.length==1

        &&String.class.equals(parameterTypes[0])

        &&exceptionTypes.length==1

        &&NullPointerException.class.equals(exceptionTypes[0]);

        }

        });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值