註解的詳解和自定義

2021-07-25 07:56:14 字數 1373 閱讀 5776

什麼是註解?

註解不是注釋(comment:注釋)是jdk1.5後出現的新技術。

annotation的作用?

不是程式本身,可以對程式作出解釋。(注釋的作用)

可以被其他程式讀取

annotation的格式?

註解是以「@注釋名」在**中存在,還可以新增一些引數值。

annotation的使用範圍?

可以註解在方法,類,屬性上面。

內建註解(1)

@override 重寫的註解。

詳談@override源**如下:

@target(elementtype.method)//只用於方法前面

@retention(retentionpolicy.source)//保留

public @inte***ce override

@deprecated 不推薦使用註解。

@suppresswarnings 註解中的引數寫法 suppresswarnings中string values();這就是引數型別string和values()引數;

詳談@suppresswarnings 源**如下:讓我們的**更加清爽。

@target()//可以用於型別,方法,檔案,列舉前面

@retention(retentionpolicy.source)

public @inte***ce suppresswarnings

怎麼樣自定義註解:

@target 用於描述註解的使用範圍(即:被描述的註解可以用在什麼地方)。

@retention 保留的策略。retentionpolicy,source(在原始檔中有效) ,class(在類中有效),runtime(在執行時有效)。

下面乙個自定義註解類的範例:

@target(value=)

@retention(retentionpolicy.runtime);

public @inte***ce sxtannotation01;

}下面第二個之定義註解

@target(value=)

@retention(retentionpolicy.runtime)

public @inte***ce sxtannotation02

註解在另外乙個類中的使用:

@sxtannotation01

public class demo02)

public void test01()

@sxtannotation02("aaa")//沒有預設值就會要求新增值,他可以這樣寫例如@sxtannotation02(value=「aaa」)

public void test02()

}註解的作用,註解的作用則需要解析才會產生作用。(後面文章會提及到反射機制解析註解)

自定義註解

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...