Java Annotation,Java註解

來源:互聯網
上載者:User

Annotation

Annotaions (also known as metadata) provide a formalized way to add information to yourcode so that you can easily use that data at some later point.
Defining annotationsHere is the definition of the annotation above. You can see that annotation definitions look a lot like interface definitions.

In fact, they compile to class files like any other Java interface:Apart from the @ symbol, the definition of @Test is much like that of an empty interface.

An annotation definition also requires the meta-annotations @Target and @Retention.

@Target defines where you can apply this annotation(a method or a field, for example).

@Retention defines whether the annotations are availablein the (SOURCE), in the classfiles (CLASS), or at run time(RUNTIME).

e.g.:

//UseCase.javapackage annotationtest;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface UseCase {public int id();public String description() default "沒有描述";}//PasswordUtils.javapackage annotationtest;public class PasswordUtils {@UseCase(id=1, description="validate 密碼")public boolean validatePassword(String password){return true;}@UseCase(id=2, description="encrypt 密碼")public boolean encryptPassword(String password){return true;}@UseCase(id=3, description="checkfor 密碼")public boolean checkforPassword(String password){return true;}}//Test.javapackage annotationtest;import java.lang.reflect.Method;public class Test {/** * @param args */public static void main(String[] args) {Method[] methods = PasswordUtils.class.getDeclaredMethods();for (Method m : methods) {UseCase uc= m.getAnnotation(UseCase.class);System.out.println("id=" + uc.id()+",description="+uc.description());}}}// from : thinking in 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.