自定義註解理解梳理

2021-07-05 17:48:42 字數 1381 閱讀 7266

自定義註解的使用很簡單,通過@inte***ce修飾就可以稱之為註解,但是在使用的時候,卻有很多門道。

限制輸入

首先,自定義註解可以用來限制輸入。例如:

@target(elementtype.method)

@retention(retentionpolicy.runtime)

@documented

public @inte***ce

annotationself ;

fieldtype type();

string value();

}

在這個例子中,我們限制了type的型別是列舉值,而value的型別是string型別。

在使用的時候,會強制我們使用限定的值。例如:

@annotationself(type = fieldtype.string, value = "9")

void useannotation()

在該例中,就要求限制type只能輸入列舉fieldtype中的值,而value只能是string型別的值。

使用反射獲取註解內容

其次,使用註解可以通過反射的方式獲取到註解的內容,

object c = class.forname("com.wyb.annotation.user.usertest")

.newinstance();

method methodarray = c.getclass().getdeclaredmethods();

上面**可以獲取到類所有方法。

methodarray[i].isannotationpresent((class

<? extends

annotation>)annotationself.class)

這時isannotationpresent這個方法就有作用了,該方法可以判斷獲取到的方法是否是用annotationself這個註解過的。同理,可以通過該方法來篩選出感興趣的方法。之後就可以通過以下**來獲取需要的資訊了。

annotationself annotation = 

methodarray[i].getannotation(annotationself.class);

string

type = string.valueof(annotation.type());

注:

上面**中annotationself 是自定義註解,

com.wyb.annotation.user.usertest是測試類。

自定義註解

target elementtype.field retention retentionpolicy.runtime public inte ce setvalue以上就是乙個自定義的註解,下面來進行說明。target elementtype.field 表示支援該註解的程式元素,field就是屬性...

自定義註解

三個重要元註解 target 即註解的作用域,用於說明註解的使用範圍 即註解可以用在什麼地方,比如類的註解,方法註解,成員變數註解等等 elemenettype.constructor 構造器宣告 elemenettype.field 域宣告 包括 enum 例項 elemenettype.loca...

自定義註解

三個重要元註解 target 即註解的作用域,用於說明註解的使用範圍 即註解可以用在什麼地方,比如類的註解,方法註解,成員變數註解等等 elemenettype.constructor 構造器宣告 elemenettype.field 域宣告 包括 enum 例項 elemenettype.loca...