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

Posted on 2020-03-10 00:53  GLLegolas  阅读(3824)  评论(0编辑  收藏  举报

需求假设:假设在包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