Java注釋(Annotation)

來源:互聯網
上載者:User

Java5中提供了新的注釋(Annotation),能夠為類提供額外資訊,本文介紹了如何定義注釋、如何使用注釋和如何解析注釋。

1、定義注釋

package ch5;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

// 注釋什麼時候起作用包括兩種:RetentionPolicy.RUNTIME(編譯並且在啟動並執行時候可以找到),
// RetentionPolicy.SOURCE(編譯的時候將被忽略)
@Retention(RetentionPolicy.RUNTIME)
// Target指出注釋使用的地方:類或者介面上(ElementType.TYPE),
// 方法上(ElementType.METHOD),
// 屬性上(ElementType.FIELD)
@Target({ElementType.TYPE})
public @interface Table {
 String name();
}

2、使用注釋

package ch5;

@Table(name = "user")
public class UserBean {
 private String id;
 private String name;
}

3、解析注釋

package ch5;

import java.lang.annotation.Annotation;

public class UserManger {
 private UserBean user;
 public static void main(String[] args) {
  System.out.println(new UserManger().getTable());
 }
 
 /*
  * 擷取注釋資訊
  */
 public String getTable(){
  // 得到所有注釋
  Annotation[] annotations = UserBean.class.getAnnotations();
  // 遍曆
  for(Annotation annotation:annotations){
   // 看看是否有特定的注釋
   if(annotation instanceof Table){
    return ((Table) annotation).name();
   }
  }
  return null;
 }
}

 

李緒成 CSDN Blog:http://blog.csdn.net/javaeeteacher
CSDN學生大本營:http://student.csdn.net/space.php?uid=124362
如果喜歡我的文章,就加我為好友:http://student.csdn.net/invite.php?u=124362&c=7be8ba2b6f3b6cc5

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.