Java 使用反射如何获取当前类或者方法?

 @Pointcut("execution(* com.sss.testtest.controller..*.*(..))")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();
        String uri = request.getRequestURI();
        String logInfo = "请求uri=" + uri;
        logger.debug(logInfo);
        }

如上:
(1)可以通过,如下代码获取当前请求,获取到当前请求以后,我们可以获取到当前请求的参数等信息。比如说请求的uri

ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

获取请求中的uri:

String uri = request.getRequestURI();

(2)获取当前类的方式:通过反射拿到当前类。

 Class clazz = point.getTarget().getClass();

(3)获取当前方法:

MethodSignature methodSignature = (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();

扩展:
假设我自定义了一个注解@MenCodeChecker(作用于类上面)。现在我想,通过注解拿到我想要的信息。那么需要先通过反射拿到当前类,然后才能获取到相关的信息:

 MenCodeChecker checker = (MenCodeChecker) clazz.getDeclaredAnnotation(MenCodeChecker.class);

其中clazz就是(2)中拿到的当前类

你可能感兴趣的:(小记)