package com.self; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Iterator; import com.self.A.type; import com.self.Yts.YtsType; @A(classType=type.service) @B(getName="helo") public class AnnoTest { @B(getName="新名字") public void sayHello(String name) { System.out.println(name+" the world"); } public static void main(String[] args) throws Exception { ParseAnno anno = new ParseAnno(); anno.parseMethod(AnnoTest.class); anno.parseClass(AnnoTest.class); } } @Documented @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @interface A { public enum type{util,dao,service} public type classType() default type.util; } @Documented @Target({ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited @interface B { public String getName() default ""; } class ParseAnno { public void parseClass(Class clazz) { Object temp = (A)clazz.getAnnotation(A.class); if(temp!=null && temp instanceof A) { A a = (A)clazz.getAnnotation(A.class); System.out.println(a.classType().equals(A.type.util)); } if(temp!=null && temp instanceof B) { B b = (B) temp; System.out.println(b.getName()); } } public void parseMethod(Class clazz) throws Exception { Object obj = clazz.getConstructor(new Class[]{}).newInstance(new Object[]{}); for(Method method: clazz.getDeclaredMethods()) { B b = method.getAnnotation(B.class); if(b!=null) { try { method.invoke(obj, b.getName()); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
自定义注解@Retention,@Target, @Documented等用法实例
最新推荐文章于 2024-04-21 12:40:24 发布