自定義注解(@Alias):
package com.nf.lc.demo3; import java.lang.annotation.*; /* 定義注解的生命周期元注解:@Retention RetentionPolicy.SOURCE 在編譯階段丟棄,編譯結束沒有任何意義 RetentionPolicy.CLASS 在類加載時丟棄,字節碼文件處理時有用,默認這種方式 ☆ RetentionPolicy.RUNTIME 始終不會丟棄,運行時期也保留該注解,可以通過反射機制讀取該信息 */ @Retention(RetentionPolicy.RUNTIME) /* 定義注解的使用位置:@Target 默認可以使用在任何元素上 ElementType.CONSTRUCTOR 用於描述構造器 ElementType.FIELD 成員變量、對象、屬性(包括enum實例) ElementType.LOCAL_VARIABLE 用於描述局部變量 ElementType.METHOD 用於描述方法 ElementType.PACKAGE 用於描述包 ElementType.PARAMETER 用於描述參數 ElementType.TYPE 用於描述類、接口(包括注解類型)或enum聲明 */ @Target(value = {ElementType.FIELD,ElementType.TYPE}) /* 注解 : @Documented 表示是否將注解信息添加在Java文檔中 */ /* 注解 : @Inherited 闡述了某個被標注的類型是被繼承的,如果一個 使用了 @Inherited 修飾的annotation類型被用於一個class,則這個 annotation將被用於該class子類 */ public @interface Alias { //注解成員,default表示默認值 public String value() default ""; //注解成員,是否參與代碼生成 public boolean isGenerator() default true; }
實體類(Product):
package com.nf.lc.demo3; import java.math.BigDecimal; /** * 產品 bean 、實體、模型 */ @Alias(value = "products" , isGenerator = true) public class Product { @Alias(value = "pro_id" , isGenerator = false) private int id;
@Alias(value = "pro_name") private String name; private BigDecimal price; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } }
啟動類Main方法:
package com.nf.lc.demo3; import java.lang.reflect.Field; public class Main { public static void main(String[] args) throws ClassNotFoundException { // 反射獲得 class Class<?> clazz = Class.forName("com.nf.lc.demo3.Product"); // 如果類 Product 上有注解 @Alias ,取出注解 value的值 Alias declaredAnnotation = clazz.getDeclaredAnnotation(Alias.class); if(declaredAnnotation != null){ System.out.println("類Product的注解@Alias的value值是:"+declaredAnnotation.value()); } //獲得所有該類方法,不包括從其他地方繼承過來的 Field[] declaredFields = clazz.getDeclaredFields(); for (Field declaredField : declaredFields) { Alias fieldAnnotation = declaredField.getDeclaredAnnotation(Alias.class); if(fieldAnnotation != null){ System.out.println("字段"+ declaredField.getName() +"有注解,注解的value值是:"+fieldAnnotation.value() +" 注解的isGenerator的值是:"+fieldAnnotation.isGenerator()); } else { System.out.println("字段"+declaredField.getName()+"沒有注解"); } } } }
運行結果:
歸途(LC)