美文网首页
使用Method类获取方法的全名称

使用Method类获取方法的全名称

作者: 雁归来兮 | 来源:发表于2018-06-02 17:48 被阅读0次

更多关于Java方面的文章,欢迎访问燕归来https://www.zhoutao123.com

需求假设:假设在包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是私有的,我们怎么拿到它呢?
幸运的是,我们发现了下面的方法


    /**
     * {@inheritDoc}
     */
    @Override
    public Class<?> getDeclaringClass() {
        return clazz;
    }
    

那么结果


结果 = 类名全称 +"."+方法名
结果 = method.getDeclaringClass().getName()+"."+method.getName()

更多关于Java方面的文章,欢迎访问燕归来https://www.zhoutao123.com

相关文章

网友评论

      本文标题:使用Method类获取方法的全名称

      本文链接:https://www.haomeiwen.com/subject/ftwrsftx.html