* 获取指定方法的参数名
*
* @param method 要获取参数名的方法
* @return 按参数顺序排列的参数名列表
*/
public static List<RequestParam> getMethodParameterNamesByAnnotation(Method method) {
List<RequestParam> result = new ArrayList<>();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
if (parameterAnnotations == null || parameterAnnotations.length == 0) {
return null;
}
for (Annotation[] parameterAnnotation : parameterAnnotations) {
for (Annotation annotation : parameterAnnotation) {
if (annotation instanceof RequestParam) {
RequestParam param = (RequestParam) annotation;
result.add(param);
}
}
}
return result;
}
1、上面这个方法可以获取到那些参数有加注解
2、通过名称反射方法,不需要参数,可以解决没有参数时反射方法的问题,不允许同一个类中有同名的方法
Method[] methods = o.getClass().getMethods();
Method method = null;
for (Method methodTemp : methods) {
String name = methodTemp.getName();
if(name.equals(actionName)) {
method = methodTemp;
break;
}
}
3、同时需要获取到这个方法的参数类型,因为注入时需要知道参数类型
Class<?>[] parameterTypes = method.getParameterTypes();
4、注解 RequestParam,这个是复制spring的注解声明
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestParam {
String value() default "";
String name() default "";
boolean required() default true;
String defaultValue() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";
}
5、最后就是拿到参数然后进行注入,反射调用
Entry<RequestParam, Class<?>> next = iterator.next();
Class<?> value = next.getValue();
RequestParam key = next.getKey();
Object parameter = null;
String requestParam = webInput.getParameter(key.value());
if(requestParam != null) {
if(value.getName().equalsIgnoreCase(Integer.class.getName())) {
parameter = Integer.parseInt(requestParam);
}
}
boolean required = key.required();
if(required && parameter == null) {
throw new AppRuntimeException(key.value() + " is not allow null value!");
}
params.add(parameter);
mex.getMethod().invoke(this, params.toArray());