注解(Annotation)
注解:是JDK1.5的新特性。相当于一种标记,在程序上加了它就等于为程序打上了某种标记,以后java编译器,开发工具和其他程序可以用反射来了解你的类及各种元素上有无何种标记,以便于进行下一步相应的操作。
标记可以加在包、类、方法、字段、方法的参数以及局部变量上。
几个基本的注解:
1、@SuppressWarnings(“deprecation) //压缩警告,告诉编译器不再提示方法过时。
2、@Deprecated //标记过时,例如标记以下方法已过时了,其他程序调用就会提示此为过时方法。
3、@Override //标记子类复写的父类的某个方法。(可以用来检测是否写正确,不正确的话,覆盖父类方法失败)。
关于注解的问题及理解:
由于编译完源文件后会去掉一部分注解,用类加载器加载class文件进内存后变成的二进制数据才是字节码文件,而编译器拿到的是二进制的字节码,所以会产生明明加了注解但利用反射技术却得不到该类身上的注解。
注解的存在位置(不准确)分为三部分:java源文件——>class文件——>内存中的字节码。
分别对应三种取值:RetentionPolicy.SOURCE、RetentionPolicy.CLASS、RetentionPolicy.RUNTIME。
自定义注解及在注解上添加相应的属性信息:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
//添加自定义注解
@MyAnnotationForTest(classAttr=String.class,annotationAttr=@MyMetaAnnotation("itheima"),color="green",value="cyx",arrayAttr={1,3})
public class MyAnnotationTest
{
private String string = "abc";
//基本注解之一:标记方法已过时
@Deprecated
public static void printString(String string)
{
System.out.println(string);
}
//基本注解之二:子类复写父类方法
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((string == null) ? 0 : string.hashCode());
return result;
}
//基本注解之三:压缩警告,不再提示方法过时
@SuppressWarnings("deprecation")
public static void main(String[] args)
{
System.runFinalizersOnExit(true);
String string = "12345";
printString(string);
//判断MyAnnotationTest类中是否有MyAnnotationForTest类型的注解。
if(MyAnnotationTest.class.isAnnotationPresent(MyAnnotationForTest.class))
{
//通过反射技术,获得MyAnnotationForTest类型注解,并操作注解内的属性。
MyAnnotationForTest annotationForTest =
(MyAnnotationForTest)MyAnnotationTest.class.getAnnotation(MyAnnotationForTest.class);
System.out.println(annotationForTest.color());
System.out.println(annotationForTest.value());
System.out.println(annotationForTest.arrayAttr().length);
System.out.println(annotationForTest.classAttr().getName());
System.out.println(annotationForTest.annotationAttr().value());
}
}
}
//让注解信息保留到运行时期。
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotationForTest
{
String color() default "yellow";//对属性添加缺省值
String value();
int[] arrayAttr();//数组类型
Class<?> classAttr();//Class类型
//@MyMetaAnnotation代表MyMetaAnnotation的一个实例对象
MyMetaAnnotation annotationAttr() default @MyMetaAnnotation("heima");//注解类型
}
public @interface MyMetaAnnotation
{
String value();
}
运行结果:
12345
green
cyx
2
java.lang.String
itheima