java注解(上)
JDK1.5新特性:注解
相當(dāng)于一種標(biāo)記,加上注解就等同加上了某種標(biāo)記,以后javac編譯器、開發(fā)工具和其他程序可以用反射來(lái)了解這個(gè)類及各種元素上有無(wú)何種標(biāo)記。有什么標(biāo)記、就去干相應(yīng)的事
標(biāo)記可以加在:包、類、字段、方法、方法的參數(shù)以及局部變量上
java.lang包,可看到JDK中提供的最基本的Annotation
@Override
@Deprecated
@SuppressWarnings
表示關(guān)閉一些不當(dāng)?shù)木幾g器警告信息
注解也相當(dāng)于一個(gè)特殊的類
注解的應(yīng)用結(jié)構(gòu)圖:
注解類
應(yīng)用了“注解類”的類
@interface A{
@A
class C{
}
class
B{
B.class.isAnnotationPresent(A.class);
a = B.class.getAnnotation(A.class);
}
元注解:為注解提供服務(wù)的注解稱為~
@Retention(RetentionPolicy.RUNTIME)
它的作用:使注解一直保留到一個(gè)時(shí)期,決定注解的生命周期,默認(rèn)是CLASS
RetentionPolicy是一個(gè)枚舉,其中有三種取值:
分別對(duì)應(yīng)
RetentionPolicy.SOURCE
RetentionPolicy.CLASS
RetentionPolicy.RUNTIME
當(dāng)編譯器編譯java源文件時(shí),可能會(huì)把“沒用的”注解從中去掉,編譯成class
當(dāng)使用該類時(shí),類加載器把class文件加載到內(nèi)存中時(shí),也會(huì)把“沒用的”注解從中去掉,生成內(nèi)存中的字節(jié)碼
-------------------------------------------
@Retention(RetentionPolicy.RUNTIME)
//指定注解生命周期
@Target({ElementType.METHOD,ElementType.TYPE})
//指定注解作用的范圍
public @interface MyAnnotation {
}
-------------------------------------------
java自帶的3個(gè)注解:
@Override
@SupperessWarning -->SOURCE
@Deprecated --> RUNTIME
@Target(ElementType.METHOD) 注解:
指定注解的作用范圍,如方法前,等
-------------------------------------------
@MyAnnotation
public class AnnotationTest {
main(String[] args) {
stub
//過(guò)時(shí)方法
//哪個(gè)注解在不在
AnnotationTest.class.getAnnotation(MyAnnotation.class);
static void sayHello(){
-------------------------------------------
JDK1.5中,Interface Type接口
Class也實(shí)現(xiàn)了該接口,Type更準(zhǔn)確,包含:Class interface enum
posted on 2012-04-22 15:57 hantai 閱讀(170) 評(píng)論(0) 編輯 收藏