01.學習java中的@interface

來源:互聯網
上載者:User

標籤:reflect   ram   使用   引入   rem   eric   ida   least   OLE   

  • 註解是眾多引入到Java SE5中的重要的語言變化之一。
  • Java1.6內建了三種標準註解和四種元註解(元註解專職負責註解其他註解)。
  • 大多數時候我們都是定義自己的註解,並編寫自己的處理器來處理它們。

 

  • @Target(ElementType.METHOD)
package java.lang.annotation;/** * @author  Joshua Bloch * @since 1.5 * @jls 9.6.4.1 @Target * @jls 4.1 The Kinds of Types and Values */public enum ElementType {    /** Class, interface (including annotation type), or enum declaration */    TYPE,    /** Field declaration (includes enum constants) */    FIELD,    /** Method declaration */    METHOD,    /** Formal parameter declaration */    PARAMETER,    /** Constructor declaration */    CONSTRUCTOR,    /** Local variable declaration */    LOCAL_VARIABLE,    /** Annotation type declaration */    ANNOTATION_TYPE,    /** Package declaration */    PACKAGE,    /**     * Type parameter declaration     *     * @since 1.8     */    TYPE_PARAMETER,    /**     * Use of a type     *     * @since 1.8     */    TYPE_USE}
View Code
  •  @Retention(RetentionPolicy.RUNTIME)
package java.lang.annotation;/** * @author  Joshua Bloch * @since 1.5 */public enum RetentionPolicy {    /**     * Annotations are to be discarded by the compiler.     */    SOURCE,    /**     * Annotations are to be recorded in the class file by the compiler     * but need not be retained by the VM at run time.  This is the default     * behavior.     */    CLASS,    /**     * Annotations are to be recorded in the class file by the compiler and     * retained by the VM at run time, so they may be read reflectively.     *     * @see java.lang.reflect.AnnotatedElement     */    RUNTIME}
View Code
  • 定義註解
@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface UseCase {    public int id();    public String description() default "no description";}

 

  • 使用註解
public class PasswordUtils {    @UseCase(id = 47, description =            "Passwords must contain at least one numeric")    public boolean validatePassword(String password) {        return (password.matches("\\w*\\d\\w*"));    }    @UseCase(id = 48)    public String encryptPassword(String password) {        return new StringBuilder(password).reverse().toString();    }    @UseCase(id = 49, description =            "New passwords can‘t equal previously used ones")    public boolean checkForNewPassword(            List<String> prevPasswords, String password) {        return !prevPasswords.contains(password);    }}

 

  • 編寫註解處理器
public class UseCaseTracker {    public static void trackUseCases(List<Integer> useCases, Class<?> cl) {        for (Method m : cl.getDeclaredMethods()) {            UseCase uc = m.getAnnotation(UseCase.class);            if (uc != null) {                System.out.println("Found Use Case: " + uc.id() + " " + uc.description());                useCases.remove(new Integer(uc.id()));            }        }        for (int i : useCases) {            System.out.println("Warning: Missing use case-" + i);        }    }    public static void main(String[] args) {        List<Integer> useCases = new ArrayList<Integer>();        Collections.addAll(useCases, 47, 48, 49, 50);        trackUseCases(useCases, PasswordUtils.class);    }}
  • 運行結果:
Found Use Case: 47 Passwords must contain at least one numericFound Use Case: 48 no descriptionFound Use Case: 49 New passwords can‘t equal previously used onesWarning: Missing use case-50

 

幾個注意點:
  • 標籤@UseCase由UseCase.java定義,其中包括int元素id,以及一個String元素description。

  • 註解元素可用的類型如下(否則編譯器報錯):

    • 所有基本類型(int, float, boolean等)
    • String
    • Class
    • enum
    • Annotation
    • 以上類型的數組
  • 註解元素必須要麼具有預設值,要麼在使用註解時提供元素的值。

  • 註解不支援繼承。(見Thinking in Java Fourth Edition 20.2.4)

參考:
  • Thinking in Java Fourth Edition (Bruce Eckel)

 

01.學習java中的@interface

聯繫我們

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