天天看點

java注解

注解是什麼?

注解是一種語言形式而已,類似于接口、枚舉這些語言形式。

java注解

類,枚舉,接口,注解都是一種語言形式,他們是平行的,既然有形式,那麼就應當有規範。

“類”的形式    class  類名

“接口”的形式    interface 接口名

“枚舉”的形式  enum 枚舉名

“注解”的形式  @interface 注解名

由于類是使用最多的一種形式,是以裡面的規則是比較多的,規則多了變化就多,各種結構,模式,通路控制就可能産生。除了“類”之外的其他三個哥們兒都有些嗜好,進行了一些看起來怪怪的規定,以滿足他們幹活時特殊的需求。
接口有接口的規則,如所有的方法都是公有的、抽象的。 枚舉有枚舉的規則,如枚舉元素必須寫在枚舉大括号的第一行;枚舉實作抽象方法的方式。等等。 注解有注解的規則,如 @Target告訴編譯器這個注解可以寫在哪些成員身上(類,方法,成員變量,局部變量,構造器,包,參數等等詳見java語言規範)  ,  @Retention來指定注解保持到什麼時期(源代碼時期,Class時期,在jvm運作期),為了簡便起見使用注解時給value指派時可以不用寫”value=”。

111

blue

2 3 4

GREEN:200

fxx

class java.lang.String

1.張孝祥老師的視訊

I N release 1.5, two families of reference types were added to the language: a new

kind of class called an enum type, and a new kind of interface called an annotation

type. This chapter discusses best practices for using these new type families.

Item 30: Use enums instead of int constants

An enumerated type is a type whose legal values consist of a fixed set of con-

stants, such as the seasons of the year, the planets in the solar system, or the suits

in a deck of playing cards. Before enum types were added to the language, a com-

mon pattern for representing enumerated types was to declare a group of named

int constants, one for each member of the type:

// The int enum pattern - severely deficient!

public static final int APPLE_FUJI  = 0;

public static final int APPLE_PIPPIN  = 1;

public static final int APPLE_GRANNY_SMITH = 2;

public static final int ORANGE_NAVEL  = 0;

public static final int ORANGE_TEMPLE = 1;

public static final int ORANGE_BLOOD  = 2;

This technique, known as the int enum pattern, has many shortcomings. It

provides nothing in the way of type safety and little in the way of convenience.

The compiler won’t complain if you pass an apple to a method that expects an

orange, compare apples to oranges with the == operator, or worse:

// Tasty citrus flavored applesauce!

int i = (APPLE_FUJI - ORANGE_TEMPLE) / APPLE_PIPPIN;

開始做,堅持做,重複做