How to get Method Parameter names in Java 8 using reflection?

后端 未结 4 1155
终归单人心
终归单人心 2020-11-27 03:55

Java 8 has the ability to acquire method parameter names using Reflection API.

  1. How can I get these method parameter names?

  2. As per my knowled

4条回答
  •  死守一世寂寞
    2020-11-27 04:32

    You can use Paranamer lib (https://github.com/paul-hammant/paranamer)

    Sample code that works for me:

    import com.thoughtworks.paranamer.AnnotationParanamer;
    import com.thoughtworks.paranamer.BytecodeReadingParanamer;
    import com.thoughtworks.paranamer.CachingParanamer;
    import com.thoughtworks.paranamer.Paranamer;
    
    Paranamer info = new CachingParanamer(new AnnotationParanamer(new BytecodeReadingParanamer()));
    
    Method method = Foo.class.getMethod(...);
    String[] parameterNames = info.lookupParameterNames(method);
    

    If you use Maven then put this dependency in your pom.xml:

    
        com.thoughtworks.paranamer
        paranamer
        2.8
    
    

提交回复
热议问题