註解處理器

阿飞藏泪發表於2024-03-30

demo:

/1:*** 定義註解*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitProvider {
 /**供應商編號*/
public int id() default -1;
/*** 供應商名稱*/
 public String name() default ""13/04/2018 Page 108 of 283
 /** * 供應商地址*/
 public String address() default "";
}
//2:註解使用
public class Apple {
 @FruitProvider(id = 1, name = "陝西紅富士集團", address = "陝西省西安市延安路")
 private String appleProvider;
 public void setAppleProvider(String appleProvider) {
 this.appleProvider = appleProvider;
 }
 public String getAppleProvider() {
 return appleProvider;
 }
}
/3:*********** 註解處理器 ***************/
public class FruitInfoUtil {
 public static void getFruitInfo(Class<?> clazz) {
 String strFruitProvicer = "供應商資訊:";
 Field[] fields = clazz.getDeclaredFields();//透過反射獲取處理註解
 for (Field field : fields) {
 if (field.isAnnotationPresent(FruitProvider.class)) {
 FruitProvider fruitProvider = (FruitProvider) field.getAnnotation(FruitProvider.class);
//註解資訊的處理地方 
strFruitProvicer = " 供應商編號:" + fruitProvider.id() + " 供應商名稱:"
 + fruitProvider.name() + " 供應商地址:"+ fruitProvider.address();
 System.out.println(strFruitProvicer);
 }
 }
 }
}
13/04/2018 Page 109 of 283
public class FruitRun {
 public static void main(String[] args) {
 FruitInfoUtil.getFruitInfo(Apple.class);
/***********輸出結果***************/
// 供應商編號:1 供應商名稱:陝西紅富士集團 供應商地址:陝西省西安市延
 }
}

相關文章