Created
August 7, 2019 03:39
-
-
Save ziyoung/7aa16e108e9dac5390f6973ba441f3c3 to your computer and use it in GitHub Desktop.
Java 中注解可以添加在方法的参数上
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Run { | |
@Target(ElementType.PARAMETER) | |
@Retention(RetentionPolicy.RUNTIME) | |
static @interface QueryParam { | |
String value(); | |
} | |
public void testAnnotation(@QueryParam("action") String action) { | |
System.out.printf("action is %s\n", action); | |
} | |
public static void exec() throws NoSuchMethodException { | |
Class<?> cls = Run.class; | |
Method method = cls.getMethod("testAnnotation", String.class); | |
Annotation[][] annotations = method.getParameterAnnotations(); | |
for (int i = 0; i < annotations.length; i++) { | |
Annotation[] annotations1 = annotations[i]; | |
for (Annotation annotation: annotations1) { | |
if (annotation instanceof QueryParam) { | |
QueryParam param = (QueryParam) annotation; | |
System.out.printf("annotation simple name is %s and value is %s\n", | |
param.annotationType().getSimpleName(), | |
param.value()); | |
String action = param.value() + "======="; | |
try { | |
method.invoke(new Run(), action); | |
} catch (IllegalAccessException | InvocationTargetException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment