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 Mercy
 * @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]);

        }

        });

你可能感兴趣的:(spring,java,aop)