自定义JAVA注解_深入理解Java:自定义java注解
要深入學(xué)習(xí)注解,我們就必須能定義自己的注解,并使用注解,在定義自己的注解之前,我們就必須要了解Java為我們提供的元注解和相關(guān)定義注解的語法。
元注解:
元注解的作用就是負(fù)責(zé)注解其他注解。Java5.0定義了4個(gè)標(biāo)準(zhǔn)的meta-annotation類型,它們被用來提供對(duì)其它 annotation類型作說明。Java5.0定義的元注解:
1.@Target,
2.@Retention,
3.@Documented,
4.@Inherited
這些類型和它們所支持的類在java.lang.annotation包中可以找到。下面我們看一下每個(gè)元注解的作用和相應(yīng)分參數(shù)的使用說明。
@Target:
@Target說明了Annotation所修飾的對(duì)象范圍:Annotation可被用于 packages、types(類、接口、枚舉、Annotation類型)、類型成員(方法、構(gòu)造方法、成員變量、枚舉值)、方法參數(shù)和本地變量(如循環(huán)變量、catch參數(shù))。在Annotation類型的聲明中使用了target可更加明晰其修飾的目標(biāo)。
作用:用于描述注解的使用范圍(即:被描述的注解可以用在什么地方)
取值(ElementType)有:
1.CONSTRUCTOR:用于描述構(gòu)造器
2.FIELD:用于描述域
3.LOCAL_VARIABLE:用于描述局部變量
4.METHOD:用于描述方法
5.PACKAGE:用于描述包
6.PARAMETER:用于描述參數(shù)
7.TYPE:用于描述類、接口(包括注解類型) 或enum聲明
使用實(shí)例:
@Target(ElementType.TYPE)
public @interface Table {
/**
* 數(shù)據(jù)表名稱注解,默認(rèn)值為類名稱
* @return
*/
public String tableName() default "className";
}
@Target(ElementType.FIELD)
public @interface NoDBColumn {
}
注解Table 可以用于注解類、接口(包括注解類型) 或enum聲明,而注解NoDBColumn僅可用于注解類的成員變量。
@Retention:
@Retention定義了該Annotation被保留的時(shí)間長短:某些Annotation僅出現(xiàn)在源代碼中,而被編譯器丟棄;而另一些卻被編譯在class文件中;編譯在class文件中的Annotation可能會(huì)被虛擬機(jī)忽略,而另一些在class被裝載時(shí)將被讀取(請(qǐng)注意并不影響class的執(zhí)行,因?yàn)锳nnotation與class在使用上是被分離的)。使用這個(gè)meta-Annotation可以對(duì) Annotation的“生命周期”限制。
作用:表示需要在什么級(jí)別保存該注釋信息,用于描述注解的生命周期(即:被描述的注解在什么范圍內(nèi)有效)
取值(RetentionPoicy)有:
1.SOURCE:在源文件中有效(即源文件保留)
2.CLASS:在class文件中有效(即class保留)
3.RUNTIME:在運(yùn)行時(shí)有效(即運(yùn)行時(shí)保留)
Retention meta-annotation類型有唯一的value作為成員,它的取值來自java.lang.annotation.RetentionPolicy的枚舉類型值。具體實(shí)例如下:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
public String name() default "fieldName";
public String setFuncName() default "setField";
public String getFuncName() default "getField";
public boolean defaultDBValue() default false;
}
Column注解的的RetentionPolicy的屬性值是RUTIME,這樣注解處理器可以通過反射,獲取到該注解的屬性值,從而去做一些運(yùn)行時(shí)的邏輯處理
@Documented:
@Documented用于描述其它類型的annotation應(yīng)該被作為被標(biāo)注的程序成員的公共API,因此可以被例如javadoc此類的工具文檔化。Documented是一個(gè)標(biāo)記注解,沒有成員。
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Column {
public String name() default "fieldName";
public String setFuncName() default "setField";
public String getFuncName() default "getField";
public boolean defaultDBValue() default false;
}
@Inherited:
@Inherited 元注解是一個(gè)標(biāo)記注解,@Inherited闡述了某個(gè)被標(biāo)注的類型是被繼承的。如果一個(gè)使用了@Inherited修飾的annotation類型被用于一個(gè)class,則這個(gè)annotation將被用于該class的子類。
注意:@Inherited annotation類型是被標(biāo)注過的class的子類所繼承。類并不從它所實(shí)現(xiàn)的接口繼承annotation,方法并不從它所重載的方法繼承annotation。
當(dāng)@Inherited annotation類型標(biāo)注的annotation的Retention是RetentionPolicy.RUNTIME,則反射API增強(qiáng)了這種繼承性。如果我們使用java.lang.reflect去查詢一個(gè)@Inherited annotation類型的annotation時(shí),反射代碼檢查將展開工作:檢查class和其父類,直到發(fā)現(xiàn)指定的annotation類型被發(fā)現(xiàn),或者到達(dá)類繼承結(jié)構(gòu)的頂層。
實(shí)例代碼:
/**
*
* @author peida
*
*/
@Inherited
public @interface Greeting {
public enum FontColor{ BULE,RED,GREEN};
String name();
FontColor fontColor() default FontColor.GREEN;
}
自定義注解:
使用@interface自定義注解時(shí),自動(dòng)繼承了java.lang.annotation.Annotation接口,由編譯程序自動(dòng)完成其他細(xì)節(jié)。在定義注解時(shí),不能繼承其他的注解或接口。@interface用來聲明一個(gè)注解,其中的每一個(gè)方法實(shí)際上是聲明了一個(gè)配置參數(shù)。方法的名稱就是參數(shù)的名稱,返回值類型就是參數(shù)的類型(返回值類型只能是基本類型、Class、String、enum)。可以通過default來聲明參數(shù)的默認(rèn)值。
定義注解格式:
public?@interface 注解名 {定義體}
注解參數(shù)的可支持?jǐn)?shù)據(jù)類型:
1.所有基本數(shù)據(jù)類型(int,float,boolean,byte,double,char,long,short)
2.String類型
3.Class類型
4.enum類型
5.Annotation類型
6.以上所有類型的數(shù)組
Annotation類型里面的參數(shù)該怎么設(shè)定:
第一,只能用public或默認(rèn)(default)這兩個(gè)訪問權(quán)修飾.例如,String value();這里把方法設(shè)為defaul默認(rèn)類型;
第二,參數(shù)成員只能用基本類型byte,short,char,int,long,float,double,boolean八種基本數(shù)據(jù)類型和 String,Enum,Class,annotations等數(shù)據(jù)類型,以及這一些類型的數(shù)組.例如,String value();這里的參數(shù)成員就為String;
第三,如果只有一個(gè)參數(shù)成員,最好把參數(shù)名稱設(shè)為"value",后加小括號(hào).例:下面的例子FruitName注解就只有一個(gè)參數(shù)成員。
簡單的自定義注解和使用注解實(shí)例:
1、添加一個(gè)Table注解
packagecom.description.defined;importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;/*** Created by 華天 on 2016/06/03.*/@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)public @interfaceTable {
String value();
}
2、添加一個(gè)字段注解
packagecom.description.defined;importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;/*** Created by 華天 on 2016/06/03.*/@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)public @interfaceColumn {
String value();
}
3、創(chuàng)建User類
packagecom.description.model;importcom.description.defined.Column;importcom.description.defined.Table;/*** Created by 華天 on 2016/06/03.*/@Table("user")public classUser {
@Column("user_id")private intuserId;
@Column("user_name")privateString userName;
@Column("user_email")privateString email;
@Column("user_state")privateString userState;public intgetUserId() {returnuserId;
}public void setUserId(intuserId) {this.userId =userId;
}publicString getUserName() {returnuserName;
}public voidsetUserName(String userName) {this.userName =userName;
}publicString getEmail() {returnemail;
}public voidsetEmail(String email) {this.email =email;
}publicString getUserState() {returnuserState;
}public voidsetUserState(String userState) {this.userState =userState;
}
}
4、拼裝SQL字符串
packagecom.description.dao;importcom.description.defined.Column;importcom.description.defined.Table;importcom.description.model.User;importjava.lang.reflect.Field;importjava.lang.reflect.Method;/*** Created by 10113513 on 2016/06/03.*/
public classuserDao {/*** 通過注解和反射來拼接SQL語句
*@paramobj
*@returnsql*/
private staticString query(Object obj) {
StringBuffer sb= newStringBuffer();
Class tb=obj.getClass();//獲取Table
boolean isExists = tb.isAnnotationPresent(Table.class);if (!isExists) {return null;
}//獲取表名
Table t = (Table)tb.getAnnotation(Table.class);
String tbName=t.value();
sb.append("select * from ").append(tbName).append(" where 1=1 ");//獲取字段
Field[] fArray =tb.getDeclaredFields();for(Field f : fArray) {boolean fIsExists = f.isAnnotationPresent(Column.class);if(!fIsExists){continue;
}
Column col= f.getAnnotation(Column.class);
String colName=col.value();
String filedName=f.getName();
Object filedValue= null;//獲取get方法
String getMethodName = "get"+filedName.substring(0,1).toUpperCase()+filedName.substring(1);try{
Method getMethod=tb.getMethod(getMethodName);
filedValue=getMethod.invoke(obj);
}catch(Exception e) {
e.printStackTrace();
}//判斷字段是否為空 或者是否是值是0的int類型
if (filedValue == null || (filedValue instanceof Integer && (Integer)filedValue == 0)){continue;
}else if (filedValue instanceofString){
sb.append(" and ").append(colName).append(" = '").append(filedValue).append("'");
}else if (filedValue instanceofInteger){
sb.append(" and ").append(colName).append(" = ").append(filedValue);
}else if (false){
}
}returnsb.toString();
}public static voidmain(String[] args){
User user1= newUser();
user1.setUserId(1);
user1.setUserName("劉寶華");
String sql1=query(user1);
System.out.println(sql1);
User user2= newUser();
user2.setUserName("華天");
String sql2=query(user2);
System.out.println(sql2);
}
}
總結(jié)
以上是生活随笔為你收集整理的自定义JAVA注解_深入理解Java:自定义java注解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 客厅阳台做GRG(增强型纤维石膏)圆弧其
- 下一篇: 屋内房顶出现蚂蚁怎么处理?