代码摘自:https://www.cnblogs.com/acm-bingzi/p/javaAnnotation.html
看如下代码:
package com.work.AnnotationTest; import java.lang.annotation.*; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface FruitName { String value() default ""; }
package com.work.AnnotationTest; import java.lang.annotation.*; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface FruitColor { public enum Color{BLUE,RED,GREEN}; Color fruitColor() default Color.GREEN; }
package com.work.AnnotationTest; import java.lang.annotation.*; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface FruitProvider { public int id() default -1; public String name() default ""; public String address() default ""; }
package com.work.AnnotationTest; import java.lang.reflect.Field; public class FruitInfoUtil { public static void getFruitInfo(Class<?> clazz){ String strFruitName = " 水果名称: "; String strFruitColor = " 水果颜色: "; String strFruitProvicer = " 供应商信息: "; Field[] fields = clazz.getDeclaredFields(); for (Field field:fields){ if(field.isAnnotationPresent(FruitName.class)){ FruitName fruitName = field.getAnnotation(FruitName.class); strFruitName = strFruitName+fruitName.value(); System.out.println(strFruitName); }else if (field.isAnnotationPresent(FruitColor.class)){ FruitColor fruitColor = field.getAnnotation(FruitColor.class); strFruitColor = strFruitColor+fruitColor.fruitColor().toString(); System.out.println(strFruitColor); }else if (field.isAnnotationPresent(FruitProvider.class)){ FruitProvider fruitProvider = field.getAnnotation(FruitProvider.class); strFruitProvicer = "供应商编号: "+fruitProvider.id()+" 供应商名称: " + fruitProvider.name() + " 供应商地址: "+fruitProvider.address(); System.out.println(strFruitProvicer); } } } }
package com.work.AnnotationTest; public class FruitRun { public static void main(String[] args) { FruitInfoUtil.getFruitInfo(Apple.class); } }
输出:
水果名称: Apple
水果颜色: RED
供应商编号: 1 供应商名称: 红富士 供应商地址: 上海