以下學習註解時的代碼,直接粘貼就可以運行。
註解幾點
1.自定義的註解在默認情況下自動繼承了Annotation接口。
2.Annotation是個接口,不是註解。
3.自定義的註解是註解,而不是接口。
4.自定義的註解是不能夠其他註解所繼承的。
5.註解可以修飾註解。
6.使用註解可以提取類的信息。
7.很多框架都是以註解來實現的。
8.註解是從jdk1.5版本開始後的新特性。
9.使用反射技術來獲取註解信息的時候,要注意是否是同一個類加載器,或者會導致類加載不上的bug。
以下是實現一個註解並且運行的代碼
1.自定義一個枚舉
package com.annotation;
public enum AnnotationEnum {
ADD, SUB, MUI
}
2.自定義一個註解
package com.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value = ElementType.METHOD)
// 定義註解的運行時機
@Retention(value = RetentionPolicy.RUNTIME)
// 定義註解會被編譯,保留到class文件中,同時可以通過反射方式獲取的到
@Inherited //定義該註解可以被子類繼承的,但是不能夠做反射之類的動作
public @interface MyAnnotation {
String[] hello() default "hello";// 定義默認一個值
String world();
AnnotationEnum aEnum();
}
3.定義一個使用自定義註解的類
package com.annotation;
public class MyAnnotationTest {
@MyAnnotation(hello = { "sayHello", "sayHello1" }, world = "world", aEnum = AnnotationEnum.ADD)
public void sayHello(String name) {
System.out.println(name + " say hello.");
}
public void sayHello() {
}
}
4.測試
package com.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class Client {
public static void main(String[] args) throws Exception {
MyAnnotationTest mt = new MyAnnotationTest();
Class<MyAnnotationTest> mClass = MyAnnotationTest.class;
System.out
.println("--------------Method Reflect Begin-----------------------");
Method method = mClass.getDeclaredMethod("sayHello",
new Class[] { String.class });
method.invoke(mt, new Object[] { "Jhon" });
System.out
.println("--------------Method Reflect End-----------------------");
System.out
.println("--------------Method Reflect Get Annotation Begin-----------------------");
System.out.println(method.isAnnotationPresent(MyAnnotation.class));
MyAnnotation antotation = method.getAnnotation(MyAnnotation.class);
for (String temp : antotation.hello()) {
System.out.print(temp + " ");
}
System.out.println();
System.out.println(antotation.aEnum());
System.out.println(antotation.world());
for (Annotation temp : method.getDeclaredAnnotations()) {
System.out.println(temp);
}
System.out
.println("--------------Method Reflect Get Annotation End-----------------------");
}
}
5.給自定義的註解使用@Inherited註解,讓子類可以繼承父類的註解。
package com.annotation;
public class SubMyAnnotationTest extends MyAnnotationTest {
/*
* 如果子類只是繼承父類,而不覆寫(Override)對應的使用了inherited註解的方法,則子類依然是會繼承父類對應方法的註釋的;否則如果子類覆寫
* (Override)了該方法,則對應的註解同樣會被覆蓋掉,即此時父類方法的註解將不被子類方法所繼承。
*/
@MyAnnotation(hello = { "subSayHello", "subSayHello1" }, world = "subWorld", aEnum = AnnotationEnum.ADD)
@Override
public void sayHello(String name) {
super.sayHello(name);
}
}