Java 自訂註解(Annotation)__Java

來源:互聯網
上載者:User

在上一篇文章中介紹了註解的原理和適用情境,這一篇開始如何自訂Annotation。

Annotation是不同於Class、Interface、Enum,使用@interface自訂註解時,自動繼承了java.lang.annotation.Annotation介面,由編譯器自動完成其他細節。在定義註解時,不能繼承其他的註解或介面。



1、自訂MyAnnotation

package com.example.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;//@Target({ElementType.METHOD})@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation {String name() default "abc";//指定 預設值int age();float[] grade();}


@interface用來聲明一個註解,其中的每一個方法實際上是聲明了一個配置參數。方法的名稱就是參數的名稱,傳回值類型就是參數的類型。可以通過default來聲明參數的預設值。方法傳回值類型必須為primitive(8種基礎資料型別 (Elementary Data Type))類型、Class類型、枚舉類型、Annotation類型或者由前面任意類型之一的一維數組。在這裡可以看到@Retention和@Target這樣的元註解,用來聲明註解本身的行為。@Retention用來聲明註解的保留原則,有CLASS、RUNTIME和SOURCE這三種,分別表示註解儲存在類檔案、JVM運行時刻和原始碼中。只有當聲明為RUNTIME的時候,才能夠在運行時刻通過反射API來擷取到註解的資訊。@Target用來聲明註解可以被添加在哪些類型的元素上,如類型、方法和域等。


注意:註解是不能繼承的


2、使用MyAnnotation

@MyAnnotation(name="aaa",age=24,grade={84.5f,90.0f})public boolean isPermitted(){return false;}


3、利用反射擷取註解的屬性值

package com.example.annotation;import java.lang.reflect.Method;import java.sql.Connection;public class JdbcUtils {public static void main(String[] args) {getConnection();}@DbInfo(driver="com.mysql.jdbc.Driver",url="jdbc:mysql:///test",user="root",password="root")public static Connection getConnection(){//Class clazz = JdbcUtils.class;try {Class clazz = Class.forName("com.example.annotation.JdbcUtils");//方法1Method[] methods = clazz.getMethods();for (Method method : methods) {                if(method.isAnnotationPresent(DbInfo.class)){//判斷該方法上是否有DbInfo註解                DbInfo info = (DbInfo)method.getAnnotation(DbInfo.class);                                    System.out.println("Method["+method.getName()+"],driver["+info.driver()+"],url["+info.url()+"],user["+info.user()+"],password["+info.password()+"]");                }}//方法2Method method = clazz.getMethod("getConnection", null);DbInfo dbInfo = method.getAnnotation(DbInfo.class);if(dbInfo!=null){System.out.println("Method["+method.getName()+"],driver["+dbInfo.driver()+"],url["+dbInfo.url()+"],user["+dbInfo.user()+"],password["+dbInfo.password()+"]");}} catch (ClassNotFoundException e) {e.printStackTrace();} catch (NoSuchMethodException e) {e.printStackTrace();} catch (SecurityException e) {e.printStackTrace();}return null;}}






聯繫我們

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