java 8+推荐用parameter.getannotations()获取方法参数注解,可精准关联形参与注解并支持参数名;java 7则用method.getparameterannotations()返回annotation[][],但易因签名变化出错且无法获取参数名。

在 Java 运行时通过反射获取方法参数上的注解,关键在于使用 Method.getParameterAnnotations() 和 Parameter.getAnnotations()(Java 8+ 推荐),尤其适用于参数校验(如 @NotNull、@Size、自定义校验注解)场景。
用 Parameter 获取单个参数的注解(推荐,Java 8+)
Java 8 引入了 java.lang.reflect.Parameter 类,能准确关联每个形参与其声明的注解,避免下标错位问题(比如方法有重载、泛型擦除或 varargs 时)。
- 先通过
Method.getParameters()获取Parameter[]数组,顺序与源码一致 - 对每个
Parameter调用getAnnotations()或getAnnotation(Class<t>)</t> - 需确保编译时保留注解:加上
@Retention(RetentionPolicy.RUNTIME)
示例:
@Target(ElementType.PARAMETER)<br>@Retention(RetentionPolicy.RUNTIME)<br>public @interface NotBlank { String message() default "不能为空"; }
反射读取:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
Method method = service.getClass().getMethod("updateUser", String.class, Integer.class);<br>for (Parameter param : method.getParameters()) {<br> NotBlank notBlank = param.getAnnotation(NotBlank.class);<br> if (notBlank != null) {<br> System.out.println("参数 '" + param.getName() + "' 要求不为空:" + notBlank.message());<br> }<br>}
兼容 Java 7 的方式:用 getParameterAnnotations()
该方法返回 Annotation[][],外层数组长度 = 参数个数,内层数组是第 i 个参数的所有注解。
- 索引必须严格对应参数顺序,若方法签名变化易出错
- 无法获取参数名(默认为
arg0,arg1…),除非编译加-parameters并配合Parameter.getName()(但 Java 7 不支持Parameter)
示例:
Annotation[][] annos = method.getParameterAnnotations();<br>for (int i = 0; i for (Annotation anno : annos[i]) {<br> if (anno instanceof NotBlank) {<br> System.out.println("第 " + i + " 个参数有 @NotBlank");<br> }<br> }<br>}
结合 Spring Validation 的实际校验逻辑
Spring MVC / Boot 默认使用 MethodValidationPostProcessor 和 AOP 拦截带 @Validated 的 Bean 方法。它底层正是通过 Parameter.getAnnotations() 扫描 @NotNull、@Min 等 JSR-303 注解。
- 自定义校验器需实现
ConstraintValidator,但触发校验前的元数据提取仍依赖反射 - 若手写校验逻辑(如 RPC 入参检查),建议封装工具类:
public static <t extends annotation> T findParamAnnotation(Method m, int index, Class<t> annoType)</t></t>
注意事项和常见坑
-
必须加
@Retention(RUNTIME),否则运行时不可见 -
编译需开启参数名保留:Maven 中配置
<compilerargs><arg>-parameters</arg></compilerargs>,否则Parameter.getName()返回arg0 -
泛型参数注解不能直接获取:如
void f(@NotBlank List emails),@Email属于类型使用(type use),要用Parameter.getAnnotatedType().getAnnotations() - 接口默认方法、Lambda 表达式中的方法不适用此反射流程
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










