• 从Method中获取完整类名和方法名


    需求假设:假设在包com.zhoutao.controller下有方法getKey()方法,在JavaEE中,通过AOP获得该方法的的对象method,现在通过该对象的getName方法,仅仅只能获得getKey的结果,现在我需要的是com.zhoutao.controller.getKay 那么该如何获取呢?

    查找官方API并未发现此方法,现在我们来分析下将类名和方法名分开看:

    结果 = 类名全称 +"."+方法名
    

    现在我们已经拿到方法名了,那么我们看看能不能找到这个方法的类,我们看一下Method的源码:

    public final class Method extends Executable {
        private Class<?>            clazz;
        private int                 slot;
        // This is guaranteed to be interned by the VM in the 1.4
        // reflection implementation
        private String              name;
        private Class<?>            returnType;
        private Class<?>[]          parameterTypes;
        private Class<?>[]          exceptionTypes;
        private int                 modifiers;
        // Generics and annotations support
        private transient String              signature;
        // generic info repository; lazily initialized
        private transient MethodRepository genericInfo;
        private byte[]              annotations;
        private byte[]              parameterAnnotations;
        private byte[]              annotationDefault;
        private volatile MethodAccessor methodAccessor;
    
        .....
            
    

    通过源码可以看到,内部提供了clazz,我们知道通过clazz可以获得类名,但是这个clazz是私有的,我们怎么拿到它呢?
    幸运的是,我们发现了下面的方法通过源码可以看到,内部提供了clazz,我们知道通过clazz可以获得类名,但是这个clazz是私有的,我们怎么拿到它呢?
    幸运的是,我们发现了下面的方法:

        /**
         * {@inheritDoc}
         */
        @Override
        public Class<?> getDeclaringClass() {
            return clazz;
        }
        
    
    结果 = 类名全称 +"."+方法名
    结果 = method.getDeclaringClass().getName()+"."+method.getName()
    

    转自:https://www.jianshu.com/p/2eaed4c0fa0c

    个人理解,如有错误,欢迎指正!
  • 相关阅读:
    被@ResponseBoby注释的方法在拦截器的posthandle方法中设置cookie失效的问题
    python之异常处理
    python之url编码
    python之发送邮件
    python之使用request模块发送post和get请求
    python之小技巧积累
    python之sys.argv[]
    python之MD5加密
    python之os、sys和random模块
    python之time和datetime的常用方法
  • 原文地址:https://www.cnblogs.com/gllegolas/p/12452877.html
Copyright © 2020-2023  润新知