你不能 反射无法访问局部变量,包括方法参数。
如果您需要该功能,则需要拦截方法调用,可以通过以下几种方法之一进行操作:
- AOP(AspectJ / Spring AOP等)
- 代理(JDK,CGLib等)
在所有这些中,您将从方法调用中收集参数,然后告诉方法调用执行。但是无法通过反射获得方法参数。
更新:这是一个示例方面,可让您开始使用AspectJ中基于注释的验证
public aspect ValidationAspect { pointcut serviceMethodCall() : execution(public * com.yourcompany.**.*(..)); Object around(final Object[] args) : serviceMethodCall() && args(args){ Signature signature = thisJoinPointStaticPart.getSignature(); if(signature instanceof MethodSignature){ MethodSignature ms = (MethodSignature) signature; Method method = ms.getMethod(); Annotation[][] parameterAnnotations = method.getParameterAnnotations(); String[] parameterNames = ms.getParameterNames(); for(int i = 0; i < parameterAnnotations.length; i++){ Annotation[] annotations = parameterAnnotations[i]; validateParameter(parameterNames[i], args[i],annotations); } } return proceed(args); } private void validateParameter(String paramName, Object object, Annotation[] annotations){ // validate object against the annotations // throw a RuntimeException if validation fails }}


