代码之家  ›  专栏  ›  技术社区  ›  Ayeshmantha Perera

将方法参数名称持久化为字节码,以便在使用Maven构建时通过反射可以使用它们

  •  0
  • Ayeshmantha Perera  · 技术社区  · 7 年前

    可以通过以下方式从eclipse手动完成 (窗口->首选项->Java->编译器)

    但是如何通过maven build实现这一点呢

    import java.lang.reflect.Method;  
    import java.lang.reflect.Parameter;
    
    
    public class GetParams {
    
           public static void main(String[] args) throws Exception {
                 Method method = MyInterface.class.getMethod("myway", String.class);
                 Parameter p = m.getParameters()[0];
                 System.out.println(p.isNamePresent());
                 System.out.println(p.getName());
            }  
    
            public interface MyInterface {
                 String myway(String str);
            }  
      }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Aki    7 年前

    要在生成的字节码中存储参数名,必须传递 -parameters maven-compiler-plugin :

    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <compilerArgs>
            <arg>-parameters</arg>
          </compilerArgs>
        </configuration>
      </plugin>
    </plugins>