Java自定义注解
元注解:注解的注解。
项目结构
定义FruitName注解
package com.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /* * 水果名称注解 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface FruitName { String value() default ""; }
定义FruitColor注解
package com.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /* * 水果颜色注解 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface FruitColor { public enum Color {红色,绿色,蓝色}; Color color() default Color.红色; }
定义FruitProvider注解
package com.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /* * 水果供应商注解 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface FruitProvider { String name() default ""; String address() default ""; }
定义Apple类
package com.fruit; import com.annotation.FruitColor; import com.annotation.FruitName; import com.annotation.FruitProvider; import com.annotation.FruitColor.Color; public class Apple { @FruitName("红富士") private String name; @FruitColor(color=Color.红色) private String color; @FruitProvider(name="烟台果品",address="烟台市芝罘区幸福中路") private String provider; }
定义Test类
package com.test; import java.lang.reflect.Field; import com.annotation.FruitColor; import com.annotation.FruitName; import com.annotation.FruitProvider; import com.fruit.Apple; public class Test { public static void main(String[] args) { Field[] fields = Apple.class.getDeclaredFields(); for(Field field : fields){ if(field.isAnnotationPresent(FruitName.class)){ FruitName fruitName = field.getAnnotation(FruitName.class); System.out.println("水果名称:"+fruitName.value()); }else if(field.isAnnotationPresent(FruitColor.class)){ FruitColor fruitColor = field.getAnnotation(FruitColor.class); System.out.println("水果颜色:"+fruitColor.color()); }else if(field.isAnnotationPresent(FruitProvider.class)){ FruitProvider provider = field.getAnnotation(FruitProvider.class); System.out.println("供货商:"+provider.name()+"("+provider.address()+")"); } } } }
运行结果
水果名称:红富士
水果颜色:红色
供货商:烟台果品(烟台市芝罘区幸福中路)