Java官方筆記10註解

註解

註解的作用:

  • Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
  • Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
  • Runtime processing — Some annotations are available to be examined at runtime.

註解格式,使用@

@Entity

帶key-value:

@Author(
   name = "Benjamin Franklin",
   date = "3/27/2003"
)
class MyClass { ... }

只有1個key時可以省略key:

@SuppressWarnings(value = "unchecked")
void myMethod() { ... }
@SuppressWarnings("unchecked")
void myMethod() { ... }

同時使用多個註解:

@Author(name = "Jane Doe")
@EBook
class MyClass { ... }

The annotation type can be one of the types that are defined in the java.lang or java.lang.annotation packages of the Java SE API.

哪裏能用註解

① Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements.

② Java SE 8,annotations can also be applied to the use of types

  • Class instance creation expression:

    new @Interned MyObject();
    
  • Type cast:

    myString = (@NonNull String) str;
    
  • implements clause:

    class UnmodifiableList<T> implements
      @Readonly List<@Readonly T> { ... }
    
  • Thrown exception declaration:

    void monitorTemperature() throws
      @Critical TemperatureException { ... }
    

自定義註解

使用@interface

@interface ClassPreamble {
   String author();
   String date();
   int currentRevision() default 1;
   String lastModified() default "N/A";
   String lastModifiedBy() default "N/A";
   // Note use of array
   String[] reviewers();
}

註解其實也是一種接口,只是要使用@來聲明。

使用:

@ClassPreamble (
   author = "John Doe",
   date = "3/17/2002",
   currentRevision = 6,
   lastModified = "4/12/2004",
   lastModifiedBy = "Jane Doe",
   // Note array notation
   reviewers = {"Alice", "Bob", "Cindy"}
)
public class Generation3List extends Generation2List {

// class code goes here

}

Java預置註解

@Deprecated

// Javadoc comment follows
/**
 * @deprecated
 * explanation of why it was deprecated
 */
@Deprecated
static void deprecatedMethod() { }

@Override

// mark method as a superclass method
// that has been overridden
@Override 
int overriddenMethod() { }

@SuppressWarnings

// use a deprecated method and tell 
// compiler not to generate a warning
@SuppressWarnings("deprecation")
void useDeprecatedMethod() {
    // deprecation warning
    // - suppressed
    objectOne.deprecatedMethod();
}

@SafeVarargs

@FunctionalInterface

註解上的註解:Annotations that apply to other annotations are called meta-annotations. There are several meta-annotation types defined in java.lang.annotation.

@Retention

  • RetentionPolicy.SOURCE – The marked annotation is retained only in the source level and is ignored by the compiler.
  • RetentionPolicy.CLASS – The marked annotation is retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM).
  • RetentionPolicy.RUNTIME – The marked annotation is retained by the JVM so it can be used by the runtime environment.

@Documented

@Target

@Inherited

@Repeatable

重複註解也是允許的:

@Schedule(dayOfMonth="last")
@Schedule(dayOfWeek="Fri", hour="23")
public void doPeriodicCleanup() { ... }

重複註解的定義要用到@Repeatable:

@Repeatable(Schedules.class)
public @interface Schedule {
  String dayOfMonth() default "first";
  String dayOfWeek() default "Mon";
  int hour() default 12;
}

並且,The containing annotation type must have a value element with an array type:

public @interface Schedules {
    Schedule[] value();
}

the containing annotation type is @Schedules, so repeating @Schedule annotations is stored in an @Schedules annotation.

Schedule[] value()是一個沒有參數、返回類型爲Schedule[]的方法的聲明,它是一個抽象方法。事實上,這個方法聲明是用來定義註解的屬性的,與普通方法不同的是,它沒有方法體,只有方法聲明,而方法的具體實現則由使用該註解的代碼來完成。在使用該註解時,也可以通過指定該屬性的值來進行賦值操作,例如:

@Schedules({
        @Schedule(dayOfMonth="last"),
        @Schedule(dayOfWeek="Fri", hour="23")
})
public class MyScheduledTask {
    // ...
}

在上述代碼中,我們使用了@Schedules註解,並且指定了它的value屬性,也就是給Schedule[] value()方法賦上相應的值。注意到,該屬性的值是一個註解數組,因此需要使用大括號{}將多個註解組合起來。

參考資料:

Annotations https://dev.java/learn/annotations/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章