深入理解Java注解類型(@Annotation)
Java注解是在JDK5時(shí)引入的新特性,鑒于目前大部分框架(如spring)都使用了注解簡(jiǎn)化代碼并提高編碼的效率,因此掌握并深入理解注解對(duì)于一個(gè)Java工程師是來(lái)說(shuō)是很有必要的事。本篇我們將通過(guò)以下幾個(gè)角度來(lái)分析注解的相關(guān)知識(shí)點(diǎn)
理解Java注解
實(shí)際上Java注解與普通修飾符(public、static、void等)的使用方式并沒(méi)有多大區(qū)別,下面的例子是常見的注解:
public class AnnotationDemo {
//@Test注解修飾方法A
@Test
public static void A(){
System.out.println("Test.....");
}
//一個(gè)方法上可以擁有多個(gè)不同的注解
@Deprecated
@SuppressWarnings("uncheck")
public static void B(){
}
}
通過(guò)在方法上使用@Test注解后,在運(yùn)行該方法時(shí),測(cè)試框架會(huì)自動(dòng)識(shí)別該方法并單獨(dú)調(diào)用,@Test實(shí)際上是一種標(biāo)記注解,起標(biāo)記作用,運(yùn)行時(shí)告訴測(cè)試框架該方法為測(cè)試方法。而對(duì)于@Deprecated和@SuppressWarnings(“uncheck”),則是Java本身內(nèi)置的注解,在代碼中,可以經(jīng)常看見它們,但這并不是一件好事,畢竟當(dāng)方法或是類上面有@Deprecated注解時(shí),說(shuō)明該方法或是類都已經(jīng)過(guò)期不建議再用,@SuppressWarnings 則表示忽略指定警告,比如@SuppressWarnings(“uncheck”),這就是注解的最簡(jiǎn)單的使用方式,那么下面我們就來(lái)看看注解定義的基本語(yǔ)法
基本語(yǔ)法
聲明注解與元注解
我們先來(lái)看看前面的Test注解是如何聲明的:
//聲明Test注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
}
我們使用了@interface聲明了Test注解,并使用@Target注解傳入ElementType.METHOD參數(shù)來(lái)標(biāo)明@Test只能用于方法上,@Retention(RetentionPolicy.RUNTIME)則用來(lái)表示該注解生存期是運(yùn)行時(shí),從代碼上看注解的定義很像接口的定義,確實(shí)如此,畢竟在編譯后也會(huì)生成Test.class文件。對(duì)于@Target和@Retention是由Java提供的元注解,所謂元注解就是標(biāo)記其他注解的注解,下面分別介紹
@Target 用來(lái)約束注解可以應(yīng)用的地方(如方法、類或字段),其中ElementType是枚舉類型,其定義如下,也代表可能的取值范圍
public enum ElementType {
/**標(biāo)明該注解可以用于類、接口(包括注解類型)或enum聲明*/
TYPE,
/** 標(biāo)明該注解可以用于字段(域)聲明,包括enum實(shí)例 */
FIELD,
/** 標(biāo)明該注解可以用于方法聲明 */
METHOD,
/** 標(biāo)明該注解可以用于參數(shù)聲明 */
PARAMETER,
/** 標(biāo)明注解可以用于構(gòu)造函數(shù)聲明 */
CONSTRUCTOR,
/** 標(biāo)明注解可以用于局部變量聲明 */
LOCAL_VARIABLE,
/** 標(biāo)明注解可以用于注解聲明(應(yīng)用于另一個(gè)注解上)*/
ANNOTATION_TYPE,
/** 標(biāo)明注解可以用于包聲明 */
PACKAGE,
/**
* 標(biāo)明注解可以用于類型參數(shù)聲明(1.8新加入)
* @since 1.8
*/
TYPE_PARAMETER,
/**
* 類型使用聲明(1.8新加入)
* @since 1.8
*/
TYPE_USE
}
請(qǐng)注意,當(dāng)注解未指定Target值時(shí),則此注解可以用于任何元素之上,多個(gè)值使用{}包含并用逗號(hào)隔開,如下:
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
@Retention用來(lái)約束注解的生命周期,分別有三個(gè)值,源碼級(jí)別(source),類文件級(jí)別(class)或者運(yùn)行時(shí)級(jí)別(runtime),其含有如下:
- SOURCE:注解將被編譯器丟棄(該類型的注解信息只會(huì)保留在源碼里,源碼經(jīng)過(guò)編譯后,注解信息會(huì)被丟棄,不會(huì)保留在編譯好的class文件里)
- CLASS:注解在class文件中可用,但會(huì)被VM丟棄(該類型的注解信息會(huì)保留在源碼里和class文件里,在執(zhí)行的時(shí)候,不會(huì)加載到虛擬機(jī)中),請(qǐng)注意,當(dāng)注解未定義Retention值時(shí),默認(rèn)值是CLASS,如Java內(nèi)置注解,@Override、@Deprecated、@SuppressWarnning等
- RUNTIME:注解信息將在運(yùn)行期(JVM)也保留,因此可以通過(guò)反射機(jī)制讀取注解的信息(源碼、class文件和執(zhí)行的時(shí)候都有注解的信息),如SpringMvc中的@Controller、@Autowired、@RequestMapping等。
注解元素及其數(shù)據(jù)類型
通過(guò)上述對(duì)@Test注解的定義,我們了解了注解定義的過(guò)程,由于@Test內(nèi)部沒(méi)有定義其他元素,所以@Test也稱為標(biāo)記注解(marker annotation),但在自定義注解中,一般都會(huì)包含一些元素以表示某些值,方便處理器使用,這點(diǎn)在下面的例子將會(huì)看到:
/**
* Created by wuzejian on 2017/5/18.
* 對(duì)應(yīng)數(shù)據(jù)表注解
*/
@Target(ElementType.TYPE)//只能應(yīng)用于類上
@Retention(RetentionPolicy.RUNTIME)//保存到運(yùn)行時(shí)
public @interface DBTable {
String name() default "";
}
上述定義一個(gè)名為DBTable的注解,該用于主要用于數(shù)據(jù)庫(kù)表與Bean類的映射(稍后會(huì)有完整案例分析),與前面Test注解不同的是,我們聲明一個(gè)String類型的name元素,其默認(rèn)值為空字符,但是必須注意到對(duì)應(yīng)任何元素的聲明應(yīng)采用方法的聲明方式,同時(shí)可選擇使用default提供默認(rèn)值,@DBTable使用方式如下:
//在類上使用該注解
@DBTable(name = "MEMBER")
public class Member {
//.......
}
關(guān)于注解支持的元素?cái)?shù)據(jù)類型除了上述的String,還支持如下數(shù)據(jù)類型
- 所有基本類型(int,float,boolean,byte,double,char,long,short)
- String
- Class
- enum
- Annotation
- 上述類型的數(shù)組
倘若使用了其他數(shù)據(jù)類型,編譯器將會(huì)丟出一個(gè)編譯錯(cuò)誤,注意,聲明注解元素時(shí)可以使用基本類型但不允許使用任何包裝類型,同時(shí)還應(yīng)該注意到注解也可以作為元素的類型,也就是嵌套注解,下面的代碼演示了上述類型的使用過(guò)程:
package com.zejian.annotationdemo;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by wuzejian on 2017/5/19.
* 數(shù)據(jù)類型使用Demo
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Reference{
boolean next() default false;
}
public @interface AnnotationElementDemo {
//枚舉類型
enum Status {FIXED,NORMAL};
//聲明枚舉
Status status() default Status.FIXED;
//布爾類型
boolean showSupport() default false;
//String類型
String name()default "";
//class類型
Class<?> testCase() default Void.class;
//注解嵌套
Reference reference() default @Reference(next=true);
//數(shù)組類型
long[] value();
}
編譯器對(duì)默認(rèn)值的限制
編譯器對(duì)元素的默認(rèn)值有些過(guò)分挑剔。首先,元素不能有不確定的值。也就是說(shuō),元素必須要么具有默認(rèn)值,要么在使用注解時(shí)提供元素的值。其次,對(duì)于非基本類型的元素,無(wú)論是在源代碼中聲明,還是在注解接口中定義默認(rèn)值,都不能以null作為值,這就是限制,沒(méi)有什么利用可言,但造成一個(gè)元素的存在或缺失狀態(tài),因?yàn)槊總€(gè)注解的聲明中,所有的元素都存在,并且都具有相應(yīng)的值,為了繞開這個(gè)限制,只能定義一些特殊的值,例如空字符串或負(fù)數(shù),表示某個(gè)元素不存在。
注解不支持繼承
注解是不支持繼承的,因此不能使用關(guān)鍵字extends來(lái)繼承某個(gè)@interface,但注解在編譯后,編譯器會(huì)自動(dòng)繼承java.lang.annotation.Annotation接口,這里我們反編譯前面定義的DBTable注解
package com.zejian.annotationdemo;
import java.lang.annotation.Annotation;
//反編譯后的代碼
public interface DBTable extends Annotation
{
public abstract String name();
}
雖然反編譯后發(fā)現(xiàn)DBTable注解繼承了Annotation接口,請(qǐng)記住,即使Java的接口可以實(shí)現(xiàn)多繼承,但定義注解時(shí)依然無(wú)法使用extends關(guān)鍵字繼承@interface。
快捷方式
所謂的快捷方式就是注解中定義了名為value的元素,并且在使用該注解時(shí),如果該元素是唯一需要賦值的一個(gè)元素,那么此時(shí)無(wú)需使用key=value的語(yǔ)法,而只需在括號(hào)內(nèi)給出value元素所需的值即可。這可以應(yīng)用于任何合法類型的元素,記住,這限制了元素名必須為value,簡(jiǎn)單案例如下
package com.zejian.annotationdemo;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by zejian on 2017/5/20.
*/
//定義注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface IntegerVaule{
int value() default 0;
String name() default "";
}
//使用注解
public class QuicklyWay {
//當(dāng)只想給value賦值時(shí),可以使用以下快捷方式
@IntegerVaule(20)
public int age;
//當(dāng)name也需要賦值時(shí)必須采用key=value的方式賦值
@IntegerVaule(value = 10000,name = "MONEY")
public int money;
}
Java內(nèi)置注解與其它元注解
接著看看Java提供的內(nèi)置注解,主要有3個(gè),如下:
@Override:用于標(biāo)明此方法覆蓋了父類的方法,源碼如下
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
@Deprecated:用于標(biāo)明已經(jīng)過(guò)時(shí)的方法或類,源碼如下,關(guān)于@Documented稍后分析:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public @interface Deprecated {
}
@SuppressWarnnings:用于有選擇的關(guān)閉編譯器對(duì)類、方法、成員變量、變量初始化的警告,其實(shí)現(xiàn)源碼如下:
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
String[] value();
}
其內(nèi)部有一個(gè)String數(shù)組,主要接收值如下:
- deprecation:使用了不贊成使用的類或方法時(shí)的警告;
- unchecked:執(zhí)行了未檢查的轉(zhuǎn)換時(shí)的警告,例如當(dāng)使用集合時(shí)沒(méi)有用泛型 (Generics) 來(lái)指定集合保存的類型;
- fallthrough:當(dāng) Switch 程序塊直接通往下一種情況而沒(méi)有 Break 時(shí)的警告;
- path:在類路徑、源文件路徑等中有不存在的路徑時(shí)的警告;
- serial:當(dāng)在可序列化的類上缺少 serialVersionUID 定義時(shí)的警告;
- finally:任何 finally 子句不能正常完成時(shí)的警告;
- all:關(guān)于以上所有情況的警告。
這個(gè)三個(gè)注解比較簡(jiǎn)單,看個(gè)簡(jiǎn)單案例即可:
//注明該類已過(guò)時(shí),不建議使用
@Deprecated
class A{
public void A(){ }
//注明該方法已過(guò)時(shí),不建議使用
@Deprecated()
public void B(){ }
}
class B extends A{
@Override //標(biāo)明覆蓋父類A的A方法
public void A() {
super.A();
}
//去掉檢測(cè)警告
@SuppressWarnings({"uncheck","deprecation"})
public void C(){ }
//去掉檢測(cè)警告
@SuppressWarnings("uncheck")
public void D(){ }
}
前面我們分析了兩種元注解,@Target和@Retention,除了這兩種元注解,Java還提供了另外兩種元注解,@Documented和@Inherited,下面分別介紹:
@Documented 被修飾的注解會(huì)生成到j(luò)avadoc中
/**
* Created by zejian on 2017/5/20.
*/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DocumentA {
}
//沒(méi)有使用@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DocumentB {
}
//使用注解
@DocumentA
@DocumentB
public class DocumentDemo {
public void A(){
}
}
使用javadoc命令生成文檔:
如下:

可以發(fā)現(xiàn)使用@Documented元注解定義的注解(@DocumentA)將會(huì)生成到j(luò)avadoc中,而@DocumentB則沒(méi)有在doc文檔中出現(xiàn),這就是元注解@Documented的作用。
@Inherited 可以讓注解被繼承,但這并不是真的繼承,只是通過(guò)使用@Inherited,可以讓子類Class對(duì)象使用getAnnotations()獲取父類被@Inherited修飾的注解,如下:
@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DocumentA {
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DocumentB {
}
@DocumentA
class A{ }
class B extends A{ }
@DocumentB
class C{ }
class D extends C{ }
//測(cè)試
public class DocumentDemo {
public static void main(String... args){
A instanceA=new B();
System.out.println("已使用的@Inherited注解:"+Arrays.toString(instanceA.getClass().getAnnotations()));
C instanceC = new D();
System.out.println("沒(méi)有使用的@Inherited注解:"+Arrays.toString(instanceC.getClass().getAnnotations()));
}
/**
* 運(yùn)行結(jié)果:
已使用的@Inherited注解:[@com.zejian.annotationdemo.DocumentA()]
沒(méi)有使用的@Inherited注解:[]
*/
}
注解與反射機(jī)制
前面經(jīng)過(guò)反編譯后,我們知道Java所有注解都繼承了Annotation接口,也就是說(shuō) Java使用Annotation接口代表注解元素,該接口是所有Annotation類型的父接口。同時(shí)為了運(yùn)行時(shí)能準(zhǔn)確獲取到注解的相關(guān)信息,Java在java.lang.reflect 反射包下新增了AnnotatedElement接口,它主要用于表示目前正在 VM 中運(yùn)行的程序中已使用注解的元素,通過(guò)該接口提供的方法可以利用反射技術(shù)地讀取注解的信息,如反射包的Constructor類、Field類、Method類、Package類和Class類都實(shí)現(xiàn)了AnnotatedElement接口,它簡(jiǎn)要含義如下(更多詳細(xì)介紹可以看 深入理解Java類型信息(Class對(duì)象)與反射機(jī)制):
- Class:類的Class對(duì)象定義
- Constructor:代表類的構(gòu)造器定義
- Field:代表類的成員變量定義
- Method:代表類的方法定義
- Package:代表類的包定義
下面是AnnotatedElement中相關(guān)的API方法,以上5個(gè)類都實(shí)現(xiàn)以下的方法
| 返回值 | 方法名稱 | 說(shuō)明 |
|---|---|---|
| <A extends Annotation> | getAnnotation(Class<A> annotationClass) | 該元素如果存在指定類型的注解,則返回這些注解,否則返回 null。 |
| Annotation[] | getAnnotations() | 返回此元素上存在的所有注解,包括從父類繼承的 |
| boolean | isAnnotationPresent(Class<? extends Annotation> annotationClass) | 如果指定類型的注解存在于此元素上,則返回 true,否則返回 false。 |
| Annotation[] | getDeclaredAnnotations() | 返回直接存在于此元素上的所有注解,注意,不包括父類的注解,調(diào)用者可以隨意修改返回的數(shù)組;這不會(huì)對(duì)其他調(diào)用者返回的數(shù)組產(chǎn)生任何影響,沒(méi)有則返回長(zhǎng)度為0的數(shù)組 |
簡(jiǎn)單案例演示如下:
package com.zejian.annotationdemo;
import java.lang.annotation.Annotation;
import java.util.Arrays;
/**
* Created by zejian on 2017/5/20.
*/
@DocumentA
class A{ }
//繼承了A類
@DocumentB
public class DocumentDemo extends A{
public static void main(String... args){
Class<?> clazz = DocumentDemo.class;
//根據(jù)指定注解類型獲取該注解
DocumentA documentA=clazz.getAnnotation(DocumentA.class);
System.out.println("A:"+documentA);
//獲取該元素上的所有注解,包含從父類繼承
Annotation[] an= clazz.getAnnotations();
System.out.println("an:"+ Arrays.toString(an));
//獲取該元素上的所有注解,但不包含繼承!
Annotation[] an2=clazz.getDeclaredAnnotations();
System.out.println("an2:"+ Arrays.toString(an2));
//判斷注解DocumentA是否在該元素上
boolean b=clazz.isAnnotationPresent(DocumentA.class);
System.out.println("b:"+b);
/**
* 執(zhí)行結(jié)果:
A:@com.zejian.annotationdemo.DocumentA()
an:[@com.zejian.annotationdemo.DocumentA(), @com.zejian.annotationdemo.DocumentB()]
an2:@com.zejian.annotationdemo.DocumentB()
b:true
*/
}
}
運(yùn)行時(shí)注解處理器
了解完注解與反射的相關(guān)API后,現(xiàn)在通過(guò)一個(gè)實(shí)例(該例子是博主改編自《Tinking in Java》)來(lái)演示利用運(yùn)行時(shí)注解來(lái)組裝數(shù)據(jù)庫(kù)SQL的構(gòu)建語(yǔ)句的過(guò)程
/**
* Created by wuzejian on 2017/5/18.
* 表注解
*/
@Target(ElementType.TYPE)//只能應(yīng)用于類上
@Retention(RetentionPolicy.RUNTIME)//保存到運(yùn)行時(shí)
public @interface DBTable {
String name() default "";
}
/**
* Created by wuzejian on 2017/5/18.
* 注解Integer類型的字段
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLInteger {
//該字段對(duì)應(yīng)數(shù)據(jù)庫(kù)表列名
String name() default "";
//嵌套注解
Constraints constraint() default @Constraints;
}
/**
* Created by wuzejian on 2017/5/18.
* 注解String類型的字段
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLString {
//對(duì)應(yīng)數(shù)據(jù)庫(kù)表的列名
String name() default "";
//列類型分配的長(zhǎng)度,如varchar(30)的30
int value() default 0;
Constraints constraint() default @Constraints;
}
/**
* Created by wuzejian on 2017/5/18.
* 約束注解
*/
@Target(ElementType.FIELD)//只能應(yīng)用在字段上
@Retention(RetentionPolicy.RUNTIME)
public @interface Constraints {
//判斷是否作為主鍵約束
boolean primaryKey() default false;
//判斷是否允許為null
boolean allowNull() default false;
//判斷是否唯一
boolean unique() default false;
}
/**
* Created by wuzejian on 2017/5/18.
* 數(shù)據(jù)庫(kù)表Member對(duì)應(yīng)實(shí)例類bean
*/
@DBTable(name = "MEMBER")
public class Member {
//主鍵ID
@SQLString(name = "ID",value = 50, constraint = @Constraints(primaryKey = true))
private String id;
@SQLString(name = "NAME" , value = 30)
private String name;
@SQLInteger(name = "AGE")
private int age;
@SQLString(name = "DESCRIPTION" ,value = 150 , constraint = @Constraints(allowNull = true))
private String description;//個(gè)人描述
//省略set get.....
}
上述定義4個(gè)注解,分別是@DBTable(用于類上)、@Constraints(用于字段上)、 @SQLString(用于字段上)、@SQLString(用于字段上)并在Member類中使用這些注解,這些注解的作用的是用于幫助注解處理器生成創(chuàng)建數(shù)據(jù)庫(kù)表MEMBER的構(gòu)建語(yǔ)句,在這里有點(diǎn)需要注意的是,我們使用了嵌套注解@Constraints,該注解主要用于判斷字段是否為null或者字段是否唯一。必須清楚認(rèn)識(shí)到上述提供的注解生命周期必須為@Retention(RetentionPolicy.RUNTIME),即運(yùn)行時(shí),這樣才可以使用反射機(jī)制獲取其信息。有了上述注解和使用,剩余的就是編寫上述的注解處理器了,前面我們聊了很多注解,其處理器要么是Java自身已提供、要么是框架已提供的,我們自己都沒(méi)有涉及到注解處理器的編寫,但上述定義處理SQL的注解,其處理器必須由我們自己編寫了,如下
package com.zejian.annotationdemo;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/**
* Created by zejian on 2017/5/13.
* 運(yùn)行時(shí)注解處理器,構(gòu)造表創(chuàng)建語(yǔ)句
*/
public class TableCreator {
public static String createTableSql(String className) throws ClassNotFoundException {
Class<?> cl = Class.forName(className);
DBTable dbTable = cl.getAnnotation(DBTable.class);
//如果沒(méi)有表注解,直接返回
if(dbTable == null) {
System.out.println(
"No DBTable annotations in class " + className);
return null;
}
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>();
//通過(guò)Class類API獲取到所有成員字段
for(Field field : cl.getDeclaredFields()) {
String columnName = null;
//獲取字段上的注解
Annotation[] anns = field.getDeclaredAnnotations();
if(anns.length < 1)
continue; // Not a db table column
//判斷注解類型
if(anns[0] instanceof SQLInteger) {
SQLInteger sInt = (SQLInteger) anns[0];
//獲取字段對(duì)應(yīng)列名稱,如果沒(méi)有就是使用字段名稱替代
if(sInt.name().length() < 1)
columnName = field.getName().toUpperCase();
else
columnName = sInt.name();
//構(gòu)建語(yǔ)句
columnDefs.add(columnName + " INT" +
getConstraints(sInt.constraint()));
}
//判斷String類型
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.constraint()));
}
}
//數(shù)據(jù)庫(kù)表構(gòu)建語(yǔ)句
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) + ");";
return tableCreate;
}
/**
* 判斷該字段是否有其他約束
* @param con
* @return
*/
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;
}
public static void main(String[] args) throws Exception {
String[] arg={"com.zejian.annotationdemo.Member"};
for(String className : arg) {
System.out.println("Table Creation SQL for " +
className + " is :\n" + createTableSql(className));
}
/**
* 輸出結(jié)果:
Table Creation SQL for com.zejian.annotationdemo.Member is :
CREATE TABLE MEMBER(
ID VARCHAR(50) NOT NULL PRIMARY KEY,
NAME VARCHAR(30) NOT NULL,
AGE INT NOT NULL,
DESCRIPTION VARCHAR(150)
);
*/
}
}
如果對(duì)反射比較熟悉的同學(xué),上述代碼就相對(duì)簡(jiǎn)單了,我們通過(guò)傳遞Member的全路徑后通過(guò)Class.forName()方法獲取到Member的class對(duì)象,然后利用Class對(duì)象中的方法獲取所有成員字段Field,最后利用field.getDeclaredAnnotations()遍歷每個(gè)Field上的注解再通過(guò)注解的類型判斷來(lái)構(gòu)建建表的SQL語(yǔ)句。這便是利用注解結(jié)合反射來(lái)構(gòu)建SQL語(yǔ)句的簡(jiǎn)單的處理器模型,是否已回想起hibernate?
Java 8中注解增強(qiáng)
元注解@Repeatable
元注解@Repeatable是JDK1.8新加入的,它表示在同一個(gè)位置重復(fù)相同的注解。在沒(méi)有該注解前,一般是無(wú)法在同一個(gè)類型上使用相同的注解的
//Java8前無(wú)法這樣使用
@FilterPath("/web/update")
@FilterPath("/web/add")
public class A {}
Java8前如果是想實(shí)現(xiàn)類似的功能,我們需要在定義@FilterPath注解時(shí)定義一個(gè)數(shù)組元素接收多個(gè)值如下
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface FilterPath {
String [] value();
}
//使用
@FilterPath({"/update","/add"})
public class A { }
但在Java8新增了@Repeatable注解后就可以采用如下的方式定義并使用了
package com.zejian.annotationdemo;
import java.lang.annotation.*;
/**
* Created by zejian on 2017/5/20.
*/
//使用Java8新增@Repeatable原注解
@Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(FilterPaths.class)//參數(shù)指明接收的注解class
public @interface FilterPath {
String value();
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface FilterPaths {
FilterPath[] value();
}
//使用案例
@FilterPath("/web/update")
@FilterPath("/web/add")
@FilterPath("/web/delete")
class AA{ }
我們可以簡(jiǎn)單理解為通過(guò)使用@Repeatable后,將使用@FilterPaths注解作為接收同一個(gè)類型上重復(fù)注解的容器,而每個(gè)@FilterPath則負(fù)責(zé)保存指定的路徑串。為了處理上述的新增注解,Java8還在AnnotatedElement接口新增了getDeclaredAnnotationsByType() 和 getAnnotationsByType()兩個(gè)方法并在接口給出了默認(rèn)實(shí)現(xiàn),在指定@Repeatable的注解時(shí),可以通過(guò)這兩個(gè)方法獲取到注解相關(guān)信息。但請(qǐng)注意,舊版API中的getDeclaredAnnotation()和 getAnnotation()是不對(duì)@Repeatable注解的處理的(除非該注解沒(méi)有在同一個(gè)聲明上重復(fù)出現(xiàn))。注意getDeclaredAnnotationsByType方法獲取到的注解不包括父類,其實(shí)當(dāng) getAnnotationsByType()方法調(diào)用時(shí),其內(nèi)部先執(zhí)行了getDeclaredAnnotationsByType方法,只有當(dāng)前類不存在指定注解時(shí),getAnnotationsByType()才會(huì)繼續(xù)從其父類尋找,但請(qǐng)注意如果@FilterPath和@FilterPaths沒(méi)有使用了@Inherited的話,仍然無(wú)法獲取。下面通過(guò)代碼來(lái)演示:
/**
* Created by zejian on 2017/5/20.
*/
//使用Java8新增@Repeatable原注解
@Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(FilterPaths.class)
public @interface FilterPath {
String value();
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface FilterPaths {
FilterPath[] value();
}
@FilterPath("/web/list")
class CC { }
//使用案例
@FilterPath("/web/update")
@FilterPath("/web/add")
@FilterPath("/web/delete")
class AA extends CC{
public static void main(String[] args) {
Class<?> clazz = AA.class;
//通過(guò)getAnnotationsByType方法獲取所有重復(fù)注解
FilterPath[] annotationsByType = clazz.getAnnotationsByType(FilterPath.class);
FilterPath[] annotationsByType2 = clazz.getDeclaredAnnotationsByType(FilterPath.class);
if (annotationsByType != null) {
for (FilterPath filter : annotationsByType) {
System.out.println("1:"+filter.value());
}
}
System.out.println("-----------------");
if (annotationsByType2 != null) {
for (FilterPath filter : annotationsByType2) {
System.out.println("2:"+filter.value());
}
}
System.out.println("使用getAnnotation的結(jié)果:"+clazz.getAnnotation(FilterPath.class));
/**
* 執(zhí)行結(jié)果(當(dāng)前類擁有該注解FilterPath,則不會(huì)從CC父類尋找)
1:/web/update
1:/web/add
1:/web/delete
-----------------
2:/web/update
2:/web/add
2:/web/delete
使用getAnnotation的結(jié)果:null
*/
}
}
從執(zhí)行結(jié)果來(lái)看如果當(dāng)前類擁有該注解@FilterPath,則getAnnotationsByType方法不會(huì)從CC父類尋找,下面看看另外一種情況,即AA類上沒(méi)有@FilterPath注解
/**
* Created by zejian on 2017/5/20.
*/
//使用Java8新增@Repeatable原注解
@Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited //添加可繼承元注解
@Repeatable(FilterPaths.class)
public @interface FilterPath {
String value();
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited //添加可繼承元注解
@interface FilterPaths {
FilterPath[] value();
}
@FilterPath("/web/list")
@FilterPath("/web/getList")
class CC { }
//AA上不使用@FilterPath注解,getAnnotationsByType將會(huì)從父類查詢
class AA extends CC{
public static void main(String[] args) {
Class<?> clazz = AA.class;
//通過(guò)getAnnotationsByType方法獲取所有重復(fù)注解
FilterPath[] annotationsByType = clazz.getAnnotationsByType(FilterPath.class);
FilterPath[] annotationsByType2 = clazz.getDeclaredAnnotationsByType(FilterPath.class);
if (annotationsByType != null) {
for (FilterPath filter : annotationsByType) {
System.out.println("1:"+filter.value());
}
}
System.out.println("-----------------");
if (annotationsByType2 != null) {
for (FilterPath filter : annotationsByType2) {
System.out.println("2:"+filter.value());
}
}
System.out.println("使用getAnnotation的結(jié)果:"+clazz.getAnnotation(FilterPath.class));
/**
* 執(zhí)行結(jié)果(當(dāng)前類沒(méi)有@FilterPath,getAnnotationsByType方法從CC父類尋找)
1:/web/list
1:/web/getList
-----------------
使用getAnnotation的結(jié)果:null
*/
}
}
注意定義@FilterPath和@FilterPath時(shí)必須指明@Inherited,getAnnotationsByType方法否則依舊無(wú)法從父類獲取@FilterPath注解,這是為什么呢,不妨看看getAnnotationsByType方法的實(shí)現(xiàn)源碼:
//接口默認(rèn)實(shí)現(xiàn)方法
default <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
//先調(diào)用getDeclaredAnnotationsByType方法
T[] result = getDeclaredAnnotationsByType(annotationClass);
//判斷當(dāng)前類獲取到的注解數(shù)組是否為0
if (result.length == 0 && this instanceof Class &&
//判斷定義注解上是否使用了@Inherited元注解
AnnotationType.getInstance(annotationClass).isInherited()) { // Inheritable
//從父類獲取
Class<?> superClass = ((Class<?>) this).getSuperclass();
if (superClass != null) {
result = superClass.getAnnotationsByType(annotationClass);
}
}
return result;
}
新增的兩種ElementType
在Java8中 ElementType 新增兩個(gè)枚舉成員,TYPE_PARAMETER 和 TYPE_USE ,在Java8前注解只能標(biāo)注在一個(gè)聲明(如字段、類、方法)上,Java8后,新增的TYPE_PARAMETER可以用于標(biāo)注類型參數(shù),而TYPE_USE則可以用于標(biāo)注任意類型(不包括class)。如下所示
//TYPE_PARAMETER 標(biāo)注在類型參數(shù)上
class D<@Parameter T> { }
//TYPE_USE則可以用于標(biāo)注任意類型(不包括class)
//用于父類或者接口
class Image implements @Rectangular Shape { }
//用于構(gòu)造函數(shù)
new @Path String("/usr/bin")
//用于強(qiáng)制轉(zhuǎn)換和instanceof檢查,注意這些注解中用于外部工具,它們不會(huì)對(duì)類型轉(zhuǎn)換或者instanceof的檢查行為帶來(lái)任何影響。
String path=(@Path String)input;
if(input instanceof @Path String)
//用于指定異常
public Person read() throws @Localized IOException.
//用于通配符綁定
List<@ReadOnly ? extends Person>
List<? extends @ReadOnly Person>
@NotNull String.class //非法,不能標(biāo)注class
import java.lang.@NotNull String //非法,不能標(biāo)注import
這里主要說(shuō)明一下TYPE_USE,類型注解用來(lái)支持在Java的程序中做強(qiáng)類型檢查,配合第三方插件工具(如Checker Framework),可以在編譯期檢測(cè)出runtime error(如UnsupportedOperationException、NullPointerException異常),避免異常延續(xù)到運(yùn)行期才發(fā)現(xiàn),從而提高代碼質(zhì)量,這就是類型注解的主要作用??傊甁ava 8 新增加了兩個(gè)注解的元素類型ElementType.TYPE_USE 和ElementType.TYPE_PARAMETER ,通過(guò)它們,我們可以把注解應(yīng)用到各種新場(chǎng)合中。
ok~,關(guān)于注解暫且聊到這,實(shí)際上還有一個(gè)大塊的知識(shí)點(diǎn)沒(méi)詳細(xì)聊到,源碼級(jí)注解處理器,這個(gè)話題博主打算后面另開一篇分析。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Java注解之Retention、Documented、Inherited介紹
- java教程之java注解annotation使用方法
- 5分鐘搞懂java注解@Annotation的具體使用
- Java注解Annotation與自定義注解詳解
- Java注解機(jī)制之Spring自動(dòng)裝配實(shí)現(xiàn)原理詳解
- Java注解@Transactional事務(wù)類內(nèi)調(diào)用不生效問(wèn)題及解決辦法
- 基于Java注解(Annotation)的自定義注解入門介紹
- 詳解Java注解教程及自定義注解
- 創(chuàng)建自定義的Java注解類的方法
- 輕松掌握J(rèn)ava注解,讓編程更智能、更優(yōu)雅
相關(guān)文章
java 調(diào)用wsdl協(xié)議接口簡(jiǎn)單實(shí)用方法最新推薦
文章介紹了如何使用POM導(dǎo)入依賴,并編寫一個(gè)測(cè)試類來(lái)調(diào)用不同的Web服務(wù)接口,通過(guò)訪問(wèn)接口地址,我們可以獲取請(qǐng)求和返回的body,并進(jìn)一步解析返回的JSON結(jié)果,感興趣的朋友一起看看吧2025-03-03
java批量采集豌豆莢網(wǎng)站Android應(yīng)用圖標(biāo)和包名
這篇文章主要介紹了java批量采集豌豆莢網(wǎng)站Android應(yīng)用圖標(biāo)和包名,主要用在做主題時(shí)替換這些常見應(yīng)用的圖片,需要的朋友可以參考下2014-06-06
Java?spring?MVC環(huán)境中實(shí)現(xiàn)WebSocket的示例代碼
這篇文章主要介紹了Java?spring?MVC環(huán)境中實(shí)現(xiàn)WebSocket,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-09-09
SpringBoot使用Maven打包異常-引入外部jar的問(wèn)題及解決方案
這篇文章主要介紹了SpringBoot使用Maven打包異常-引入外部jar,需要的朋友可以參考下2020-06-06
controller層如何同時(shí)接收兩個(gè)實(shí)體類
這篇文章主要介紹了controller層如何同時(shí)接收兩個(gè)實(shí)體類問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11
POI導(dǎo)出之Excel實(shí)現(xiàn)單元格的背景色填充問(wèn)題
這篇文章主要介紹了POI導(dǎo)出之Excel實(shí)現(xiàn)單元格的背景色填充問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
為Java應(yīng)用創(chuàng)建Docker鏡像的3種方式總結(jié)
Docker的使用可以將應(yīng)用程序做成鏡像,這樣可以將鏡像發(fā)布到私有或者公有倉(cāng)庫(kù)中,在其他主機(jī)上也可以pull鏡像,并且運(yùn)行容器,運(yùn)行程,下面這篇文章主要給大家總結(jié)介紹了關(guān)于為Java應(yīng)用創(chuàng)建Docker鏡像的3種方式,需要的朋友可以參考下2023-06-06
Java 將字符串動(dòng)態(tài)生成字節(jié)碼的實(shí)現(xiàn)方法
本篇文章主要是對(duì)Java將字符串動(dòng)態(tài)生成字節(jié)碼的實(shí)現(xiàn)方法進(jìn)行了介紹,需要的朋友可以過(guò)來(lái)參考下,希望對(duì)大家有所幫助2014-01-01

