获取所有注解
obj.getClass().getMethod("myMetch", String.class, int.class).getAnnotations()
package net.jeesite.java; import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; @Retention(value = RetentionPolicy.RUNTIME) @interface Meta { String length(); String name(); int age(); } @Retention(value = RetentionPolicy.RUNTIME) @interface MeTe { String length(); String name(); int age(); } public class MetaTest { @Meta(age = 0, length = "2", name = "测试注解") public static void myMetch() throws NoSuchMethodException, SecurityException { MetaTest obj = new MetaTest(); Class<?> c = obj.getClass(); System.out.println("c:" + c.getConstructors().length); Method m = c.getMethod("myMetch"); System.out.println("m:" + m.getName()); Meta meta = m.getAnnotation(Meta.class); System.out.println("meta.length():" + meta.length()); System.out.println("meta.name():" + meta.name()); System.out.println("meta.age():" + meta.age()); } @Meta(age = 30, length = "80", name = "测试带参数方法注解") @MeTe(age = 30, length = "80", name = "测试带参数方法注解") public static void myMetch(String name, int age) throws NoSuchMethodException, SecurityException { MetaTest obj = new MetaTest(); Class<?> c = obj.getClass(); System.out.println("c:" + c.getConstructors().length); Method m = c.getMethod("myMetch", String.class, int.class); System.out.println("m:" + m.getName()); Meta meta = m.getAnnotation(Meta.class); System.out.println("meta.length():" + meta.length()); System.out.println("meta.name():" + meta.name()); System.out.println("meta.age():" + meta.age()); Annotation[] a = obj.getClass().getMethod("myMetch", String.class, int.class).getAnnotations(); for (int i = 0; i < a.length; i++) { System.out.println(a[i].getClass().getName()); System.out.println(a[i]); } } public static void main(String[] args) { try { myMetch("小熊", 31); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } } }
运行结果:
c:1
m:myMetch
meta.length():80
meta.name():测试带参数方法注解
meta.age():30
net.jeesite.java.$Proxy1
@net.jeesite.java.Meta(age=30, length=80, name=测试带参数方法注解)
net.jeesite.java.$Proxy2
@net.jeesite.java.MeTe(age=30, length=80, name=测试带参数方法注解)