注解(元數(shù)據(jù))為我們在代碼中添加信息提供了一種形式化的方法,使我們能在以后方便使用這些數(shù)據(jù)宝惰。
java.lang中的注解:
· @Override
· @Deprecated
· @SuppressWarning
特點(diǎn):
- 語言級(jí)概念掌测,一旦構(gòu)造出來,就享有編譯器的類型檢查保護(hù)
- 在實(shí)際的源代碼級(jí)別保存所有的信息汞斧,而不是某種注釋性的文字粘勒。使程序員擁有對(duì)源代碼以及字節(jié)碼強(qiáng)大的檢查與操作能力
基本語法
與接口一樣,注解也會(huì)編譯成class文件庙睡。
//定義注解
@Target(ElementType.METHOD) //應(yīng)用地方
@Retention(Retention.Policy.RUNTIME) //應(yīng)用級(jí)別
public @interface UseCase {
public int id();
public String description() default "no descritpion";
}
//eg
@UseCase(id = 47, description =
"Passwords must contain at least one numeric")
public boolean validatePassword(String password) {
return (password.matches("\\w*\\d\\w*"));
}
元注解:
元注解 | - |
---|---|
@Target | ElementType參數(shù): CONSTRUCTOR:構(gòu)造器的聲明 FIELD:域聲明(包括enum實(shí)例) LOCAL_VARIABLE:局部變量聲明 METHOD:方法聲明 PACAKAGE:包聲明 PARAMETER:參數(shù)聲明 TYPE:類乘陪、接口(包括注解類型)或enum聲明 |
@Retention | 注解的生命時(shí)間 RetentionPolicy參數(shù)包括: SOURCE:源碼注解, RetentionPolicy.SOURCE : CLASS:編譯時(shí)注解啡邑,默認(rèn)值谤逼,注解在class文件中可用,但被類加載器加載字節(jié)碼到內(nèi)存時(shí)被VM丟棄流部,注解處理器 RUNTIME:運(yùn)行時(shí)注解VM將在運(yùn)行期也保留注解,因此可以通過反射讀取注解信息舞丛。 |
@Ducumented | 此注解包含在Javadoc中 |
@Inherited | 允許子類繼承父類的注解 |
注解元素:
注解包含的元素宾茂,可用類型:
- 所有基本類型
- String
- Class
- enum
- Annotation
- 以上類型的數(shù)組
默認(rèn)值限制:
注解元素不能有不確定的值跨晴,要么有默認(rèn)值片林,要么在使用注解是提供元素的值怀骤。而對(duì)于非基本類型的元素焕妙,不能使用null作為默認(rèn)值。為了繞開這個(gè)約束痕届,可以自己定義特殊的值表示某個(gè)元素不存在末患,比如空字符串或負(fù)數(shù)。
注解不支持繼承:
不能使用關(guān)鍵字extends來繼承某個(gè)@interface璧针。
繼承的注解
- | 編寫自定義注解時(shí)未寫@Inherited的運(yùn)行結(jié)果: | 編寫自定義注解時(shí)寫了@Inherited的運(yùn)行結(jié)果: |
---|---|---|
子類的類上能否繼承到父類的類上的注解探橱? | 否 | 能 |
子類方法,實(shí)現(xiàn)了父類上的抽象方法隧膏,這個(gè)方法能否繼承到注解? | 否 | 否 |
子類方法忌栅,繼承了父類上的方法曲稼,這個(gè)方法能否繼承到注解? | 能 | 能 |
子類方法瑞驱,覆蓋了父類上的方法窄坦,這個(gè)方法能否繼承到注解? | 否 | 否 |
PS: @Inherited只能注解class的注解
子類可以繼承到父類上的注解嗎--有結(jié)論了
編寫注解處理器
public class UseCaseTracker {
public static void
trackUseCases(List<Integer> useCases, Class<?> cl) {
for(Method m : cl.getDeclaredMethods()) {//獲取該類聲明的方法
UseCase uc = m.getAnnotation(UseCase.class);//返回指定類型的注解對(duì)象
if(uc != null) {
System.out.println("Found Use Case:" + uc.id() +
" " + uc.description());
useCases.remove(new Integer(uc.id()));
}
}
for(int i : useCases) {
System.out.println("Warning: Missing use case-" + i);
}
}
public static void main(String[] args) {
List<Integer> useCases = new ArrayList<Integer>();
Collections.addAll(useCases, 47, 48, 49, 50);
trackUseCases(useCases, PasswordUtils.class);
}
}
getDeclaredMethods()和getAnnotation()都屬于AnotatedElement接口,Class逆趋、Method和Field都實(shí)現(xiàn)了該接口。
@SQLString(30) //如果注解中定義了value的元素名斟,可以使用澤中快捷方式賦值
一個(gè)數(shù)據(jù)庫使用注解生成表的例子:
數(shù)據(jù)庫注解:
//表注解
@Target(ElementType.TYPE) // Applies to classes only
@Retention(RetentionPolicy.RUNTIME)
public @interface DBTable {
public String name() default "";
}
//列限制注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Constraints {
boolean primaryKey() default false;
boolean allowNull() default true;
boolean unique() default false;
}
//SQL整數(shù)
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLInteger {
String name() default "";
Constraints constraints() default @Constraints;
} ///:~
//SQL字符串
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLString {
int value() default 0;
String name() default "";
Constraints constraints() default @Constraints;
}
數(shù)據(jù)庫bean例子
@DBTable(name = "MEMBER")
public class Member {
@SQLString(30) String firstName;
@SQLString(50) String lastName;
@SQLInteger Integer age;
@SQLString(value = 30,
constraints = @Constraints(primaryKey = true))
String handle;
static int memberCount;
public String getHandle() { return handle; }
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public String toString() { return handle; }
public Integer getAge() { return age; }
} ///:~
數(shù)據(jù)庫注解處理器:
public static void main(String[] args) throws Exception {
if(args.length < 1) {
System.out.println("arguments: annotated classes");
System.exit(0);
}
for(String className : args) {
Class<?> cl = Class.forName(className);
DBTable dbTable = cl.getAnnotation(DBTable.class);
if(dbTable == null) {
System.out.println(
"No DBTable annotations in class " + className);
continue;
}
String tableName = dbTable.name();
// If the name is empty, use the Class name:
if(tableName.length() < 1)
tableName = cl.getName().toUpperCase();
List<String> columnDefs = new ArrayList<String>();
for(Field field : cl.getDeclaredFields()) {
String columnName = null;
Annotation[] anns = field.getDeclaredAnnotations();//返回注解數(shù)組
if(anns.length < 1)
continue; // Not a db table column
if(anns[0] instanceof SQLInteger) {
SQLInteger sInt = (SQLInteger) anns[0];
// Use field name if name not specified
if(sInt.name().length() < 1)
columnName = field.getName().toUpperCase();
else
columnName = sInt.name();
columnDefs.add(columnName + " INT" +
getConstraints(sInt.constraints()));
}
if(anns[0] instanceof SQLString) {
SQLString sString = (SQLString) anns[0];
// Use field name if name not specified.
if(sString.name().length() < 1)
columnName = field.getName().toUpperCase();
else
columnName = sString.name();
columnDefs.add(columnName + " VARCHAR(" +
sString.value() + ")" +
getConstraints(sString.constraints()));
}
StringBuilder createCommand = new StringBuilder(
"CREATE TABLE " + tableName + "(");
for(String columnDef : columnDefs)
createCommand.append("\n " + columnDef + ",");
// Remove trailing comma
String tableCreate = createCommand.substring(
0, createCommand.length() - 1) + ");";
System.out.println("Table Creation SQL for " +
className + " is :\n" + tableCreate);
}
}
}
private static String getConstraints(Constraints con) {
String constraints = "";
if(!con.allowNull())
constraints += " NOT NULL";
if(con.primaryKey())
constraints += " PRIMARY KEY";
if(con.unique())
constraints += " UNIQUE";
return constraints;
}
}
上述處理例子是很幼稚的(因?yàn)樾薷谋砻荒苤匦戮幾gjava代碼)闷袒,可以了解一下成熟的將對(duì)象映射到關(guān)系數(shù)據(jù)庫的方法岩梳。
使用apt處理注解
注解處理工具apt是有Sun公司提供的冀值,被設(shè)計(jì)為操作java源文件。默認(rèn)的話池摧,apt會(huì)在處理完源文件后編譯它們。如果在系統(tǒng)構(gòu)建中自動(dòng)創(chuàng)建了一些新的源文件膘魄,apt也會(huì)在新一輪檢查處理竭讳,并將所有文件一同編譯,再循環(huán)灿渴,直到?jīng)]有新源文件產(chǎn)生胰舆。使用apt時(shí)無法使用反射,因?yàn)椴僮鞯氖窃创a而不是編譯產(chǎn)生的類缚窿。
繼承AnnotationProcessor重寫process方法處理AnnotationProcessorFactory導(dǎo)出類傳進(jìn)去的AnnotationProcessorEnvironment對(duì)象倦零,該對(duì)象可以獲得注解及類信息。
補(bǔ)充: