一、注解是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