java --自訂註解的使用

來源:互聯網
上載者:User

標籤:注釋   jdk   

Annotaton(註解)是jdk5.0後引入的,先今很多主流架構都支援註解。

註解一般用於建立文檔,跟蹤代碼中的依賴以及編譯檢查。以@註解名存在


jdk中常用的註解有

@Override         覆蓋超類中方法

@Deprecated       被廢棄的代碼

@suppressWarings  警告

 

還有一些用於專門建立自訂的註解


自訂註解

@Target       應用註解位置:欄位,方法,類..

@retemtop      使用層級,(runtime,class,source)

@Documente    是否被包含在javadoc中

@Inherited      允許子類繼承父類中的註解

 

定義一個註解目的還是在於使用,使用註解最主要的部分在於對註解的處理,那麼就會涉及到註解處理器。從原理上講,註解處理器就是通過反射機制擷取被檢查方法上的註解資訊,然後根據註解元素的值進行特定的處理。

根據我們上節瞭解到的反射機制


 我們做一個註解的定義和使用


1定義註解類

importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target; @Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interfaceUseCase {     public String name();    public String desciption() default "no description";}

2定義使用者類

package com.bjpower.node.spring;public class User {private String userName;private String password;@UseCase(name = "password", desciption = "密碼")public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@UseCase(name="userName",desciption="使用者名稱")public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public User() {}public User(String username) {this.userName = username;}}

3擷取註解類方法

 public static void getrefect(String clas){ try {Class<?> cls = Class.forName(clas);//反射擷取類的Class對象Method [] methods = cls.getDeclaredMethods();//擷取類的所有方法for (Method method : methods) {//判斷方法上是否有指定的註解,有則擷取註解進行列印if(method.isAnnotationPresent(UseCase.class) == true){UseCase usercase = method.getAnnotation(UseCase.class);//擷取註解類System.out.println("使用者資訊:"+ usercase.name()+" 使用者描述:"+usercase.desciption() );}} } catch (Exception e) {e.printStackTrace();}}

4用戶端測試

public class Client {public static void main(String[] args) {getrefect("com.bjpower.node.spring.User");}}

測試結果:


使用者資訊:password使用者描述:密碼

使用者資訊:userName使用者描述:使用者名稱

 

小結:


註解的解析是利用反射,動態解析的,相比注釋,他有自己獨特的優點,我們可以對某些欄位或方法進行特別說明來對頁面資訊進行展示。



java --自訂註解的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.