@Retention(value = RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER}) @Documented public @interface Param {
/** * 参数名称 * * @return */ String value(); }
Java反射注解的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13
public static String[] getMethodParamsName(Method method) { String[] names = new String[method.getParameterAnnotations().length]; Annotation[][] parameterAnnotations = method.getParameterAnnotations(); for (int i = 0; i < parameterAnnotations.length; i++) { Annotation[] parameterAnnotation = parameterAnnotations[i]; for (Annotation annotation : parameterAnnotation) { if (annotation instanceof Param) { names[i] = ((Param) annotation).value(); } } } return names; }
Kotlin的版本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
fun getMethodParamsName(method: Method): Array<String> { val names = Array(method.parameterAnnotations.size) { "" } val parameterAnnotations = method.parameterAnnotations for (i in parameterAnnotations.indices) { val parameterAnnotation = parameterAnnotations[i] for (annotation in parameterAnnotation) { if (annotation is Param) { names[i] = annotation.value } } } return names }