一、註解是jdk1.5後加入的新特性,jdk自帶的Annotation類主要有三個:
@SuppressWarnings,可用於隱藏一些警告的提示.
用@SuppressWarnings註解後:
其實還可以用泛型消除:
public List<GirlFriend> getGirlFriends(){
List<GirlFriend> list = new ArrayList<GirlFriend>();
for(int i=0 ;i<10;i++){
GirlFriend gf = new GirlFriend();
list.add(gf);
}
return list;
}
指明集合裏要裝的元素類型
@Deprecated,此註解可作用在類、屬性及方法上.用來說明這個類、屬性或方法不再建議使用.
@Override,作用於方法上,是讓編譯器檢查這個方法是不是重寫了父類的方法,如果沒有,則編譯會報錯。這樣可以避免由於程序員不小心敲錯或敲漏字母造成的錯誤!
二、自定義Annotation
1、定義註解類MyAnnotation
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value() default "test";
EnumTest value1() default EnumTest.Welcome;
}
@Retention(RetentionPolicy.RUNTIME)的作用是標誌MyAnnotation 註解信息保留到運行期間。這樣才能使用反射獲取該註解的信息.
2、應用了"註解類"的類
@MyAnnotation(value1=EnumTest.Hello) //如果有默認值可不填參數 @MyAnnotation
public class Test {
@MyAnnotation(value="hello world",value1=EnumTest.Welcome)
public static void test(){
System.out.println("調用了test()方法");
}
}
3、對"應用了註解類的類"進行反射操作的類
public class MyReflection {
public static void main(String[] args)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, SecurityException, NoSuchMethodException{
Class<Test> clazz = Test.class;
Method method = clazz.getMethod("test",new Class[]{});
if(method.isAnnotationPresent(MyAnnotation.class)){
method.invoke(clazz, new Object[]{});//用類clazz調用的是一個靜態方法
MyAnnotation anno = method.getAnnotation(MyAnnotation.class);
System.out.println(anno.annotationType());
System.out.println(anno.value());
System.out.println(anno.value1());
Method[] ms = anno.annotationType().getDeclaredMethods();
for(Method m : ms){
System.out.println(m.getName());
}
}
}
}
打印結果:
調用了test()方法
interface annotation.MyAnnotation
hello world
Welcome
value1
value