注解和使用: 先來看下概念首先從注釋來看; 注釋:給代碼添加說明和解釋,注釋幫助開發(fā)人員理解程序。(Comment)說白點就是注釋是給人看的。 注解:給代碼添加說明解釋,這個說明給程序使用。(Annotation) 從 JDK 5.0 開始,Java 增加了對元數(shù)據(jù)(MetaData) 的支持, 也就是Annotation(注解)。 三個基本的 Annotation: @Override:限定重寫父類方法, 該注解只能用于方法 @Deprecated:用于表示某個程序元素(類, 方法等)已過時 @SuppressWarnings: 抑制編譯器警告. 什么是注解 Annotation其實就是代碼里的特殊標記, 它用于替代配置文件,也就是說,傳統(tǒng)方式通過配置文件告訴類如何運行,有了注解技術后,開發(fā)人員可以通過注解告訴類如何運行。在Java技術里注解的典型應用是:可以通過反射技術去得到類里面的注解,以決定怎么去運行類。 注解技術的要點: 如何定義注解 如何反射注解,并根據(jù)反射的注解信息,決定如何去運行類 2.1 自定義注解: 定義新的 Annotation 類型使用@interface關鍵字 聲明注解的屬性 注解屬性的作用:原來寫在配置文件中的信息,可以通過注解的屬性進行描述。 Annotation的屬性聲明方式:String name(); 屬性默認值聲明方式:Stringname() default “xxx”; 特殊屬性value:如果注解中有一個名稱value的屬性,那么使用注解時可以省略value=部分,如@MyAnnotation(“xxx") 特殊屬性value[];
注解屬性的類型可以是: String類型 基本數(shù)據(jù)類型 Class類型 枚舉類型 注解類型 以上類型的一維數(shù)組
案例演示1 創(chuàng)建和使用注解 public @interface MyAnnocation { String name(); int num() default 10; MyAnnocation2 anno(); } public @interface MyAnnocation2 { String value(); }
public class Demo1 { @MyAnnocation(name="哈哈",num=50,anno=@MyAnnocation2(value = "xxx")) public void show() { System.out.println("xxxxxxx"); } }
2.2 JDK的元 Annotation 元 Annotation指修飾Annotation的Annotation。 @Retention: 只能用于修飾一個 Annotation 定義, 用于指定該 Annotation 可以保留的域, @Rentention 包含一個 RetentionPolicy 類型的成員變量, 通過這個變量指定域。 RetentionPolicy.CLASS: 編譯器將把注解記錄在 class文件中. 當運行 Java 程序時, JVM 不會保留注解. 這是默認值 RetentionPolicy.RUNTIME:編譯器將把注解記錄在 class文件中. 當運行 Java 程序時, JVM 會保留注解. 程序可以通過反射獲取該注釋 RetentionPolicy.SOURCE: 編譯器直接丟棄這種策略的注釋
@Target:指定注解用于修飾類的哪個成員.@Target 包含了一個名為value,類型為ElementType的成員變量。 @Documented:用于指定被該元 Annotation 修飾的Annotation類將被 javadoc 工具提取成文檔。 @Inherited:被它修飾的 Annotation 將具有繼承性.如果某個類使用了被 @Inherited 修飾的Annotation,則其子類將自動具有該注解。 案例演示2 使用反射獲取注解信息 @Retention(RetentionPolicy.RUNTIME) public @interface PersonInfo { String name(); int age() default 20; String gender(); }
public class PersonOpe { @PersonInfo(name="李四",age=20,gender="男") public void show(String name,int age,String gen) { System.out.println(name); System.out.println(age); System.out.println(gen); } } public class Demo2 { public static void main(String[] args) throws Exception{ PersonOpe ope=new PersonOpe(); Class<?> class1=PersonOpe.class; Method method = class1.getMethod("show", String.class,int.class,String.class); PersonInfo annotation = method.getAnnotation(PersonInfo.class); String name=annotation.name(); int age=annotation.age(); String gender=annotation.gender(); method.invoke(ope, name,age,gender); } }
|