Java如何获取方法参数的参数名称

2025-04-18 08:58:33
推荐回答(1个)
回答1:

  • package com.mikan;  

  • import java.lang.annotation.*;  

  • /** 

  • * @author Mikan 

  • * @date 2015-08-04 23:39 

  • */  

  • @Target(ElementType.PARAMETER)  

  • @Retention(RetentionPolicy.RUNTIME)  

  • @Documented  

  • public @interface Param {  

  • String value();  

  • }  

    获取注解中的参数名的工具类:

  • package com.mikan;  

  • import java.lang.annotation.Annotation;  

  • import java.lang.reflect.Method;  

  • /** 

  • * @author Mikan 

  • * @date 2015-08-05 00:26 

  • */  

  • public class ParameterNameUtils {  

  • /** 

  • * 获取指定方法的参数名 

  • * @param method 要获取参数名的方法 

  • * @return 按参数顺序排列的参数名列表 

  • */  

  • public static String[] getMethodParameterNamesByAnnotation(Method method) {  

  • Annotation[][] parameterAnnotations = method.getParameterAnnotations();  

  • if (parameterAnnotations == null || parameterAnnotations.length == 0) {  

  • return null;  

  • }  

  • String[] parameterNames = new String[parameterAnnotations.length];  

  • int i = 0;  

  • for (Annotation[] parameterAnnotation : parameterAnnotations) {  

  • for (Annotation annotation : parameterAnnotation) {  

  • if (annotation instanceof Param) {  

  • Param param = (Param) annotation;  

  • parameterNames[i++] = param.value();  

  • }  

  • }  

  • }  

  • return parameterNames;  

  • }  

  • }  

测试类:

  • package com.mikan;  

  • import java.lang.reflect.Method;  

  • import java.util.Arrays;  

  • /** 

  • * @author Mikan 

  • * @date 2015-08-04 23:40 

  • */  

  • public class ParameterNameTest {  

  • public void method1(@Param("parameter1") String param1, @Param("parameter2") String param2) {  

  • System.out.println(param1 + param2);  

  • }  

  • public static void main(String[] args) throws Exception {  

  • Class clazz = ParameterNameTest.class;  

  • Method method = clazz.getDeclaredMethod("method1", String.class, String.class);  

  • String[] parameterNames = ParameterNameUtils.getMethodParameterNamesByAnnotation(method);  

  • System.out.println(Arrays.toString(parameterNames));  

  • }  

  • }