1.注解简介
注解是JDK1.5的新特性之一,通过使用注解我们可以在不改变原有逻辑的情况下,在源文件嵌入一些补充的信息。
注解可以用来修饰类,属性和方法,而且注解不影响程序的运行,无论是否使用注解,代码都可以正常运行。
2.系统自带的注解
2.1 @Override
覆写的注解,主要是在方法覆写的时候使用,用于保证方法覆写的真确性,它的基本使用是这样的:
public class Person {
public void sayHello(){
System.out.println("Hello Person");
}
}
public class Student extends Person{
@Override
public void sayHello() {
System.out.println("hello student");
}
}
public class Test {
public static void main(String[] args) {
Person p = new Student();
p.sayHello();
}
}
运行结果为:hello student
@override主要目的是防止用户在覆写方法时将方法名写错。
2.2@Deprecated
这个注解主要功能是用来声明一个不建议使用的方法,如果使用了此方法,在编译的时候会出现警告信息,不过虽然有警告但是并不影响运行。
2.3@SuppressWarnings
这个注解主要用来压制警告,例如在使用泛型操作的时候没有指定泛型的类型,会在编译时产生警告,此时就可以用@SuppressWarnings来压制住这种警告。例如
@SuppressWarnings("rawtypes")
public void method(){
List list = new ArrayList();
}
此时,泛型产生的警告就消失了,但是由于这个方法虽然创建了一个list但是并没有使用它,所以编译器还是会有警告,如果要压制多条警告可以这样:
@SuppressWarnings({ "rawtypes", "unused" })
public void method(){
List list = new ArrayList();
}
还有一种形式为:
@SuppressWarnings(value = { "rawtypes", "unused" })
public void method(){
List list = new ArrayList();
}
3.自定义注解
要实现一个自定义注解,必须通过
@interface
关键字来定义。且在
@interface
之前,需要通过元注解来描述该注解的使用范围(
@Target
)、生命周期(
@Retention
)
现在自定义一个注解,实现给属性默认值的功能。比如:
public class Person {
@Default(value = "zhangsan")
private String name;
public void sayHello(){
System.out.println(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
第一步,先新建一个注解:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Retention 指定注释的生存时期
* CLASS:注释记录在类文件中,但在运行时 VM 不需要保留注释。
* RUNTIME:注释记录在类文件中,在运行时 VM 将保留注释,因此可以使用反射机制读取注释内容。
* SOURCE:编译器要丢弃的注释。
*/
@Retention(RetentionPolicy.RUNTIME)
/**
* @Target
* 指示注释类型所适用的程序元素的种类,如果注释类型声明中不存在 Target 元注释,
* 则声明的类型可以用在任一程序元素上。
* ElementType.ANNOTATION_TYPE:注释类型声明
* ElementType.CONSTRUCTOR:构造方法声明
* ElementType.FILED:字段声明
* ElementType.METHOD:方法声明
*/
@Target(ElementType.FIELD)//声明这个注解是使用在字段上的
public @interface Default {
String value(); //默认值
}
解析注解:
public class Test {
public static void main(String args[]) throws Exception{
Person p = new Person();
//Default注解的处理过程
//这里使用反射机制完成默认值的设置
Field[] fileds = p.getClass().getDeclaredFields();
for(Field filed : fileds){
Default annotation = filed.getAnnotation(Default.class);
if(annotation != null){
PropertyDescriptor pd = new PropertyDescriptor(filed.getName(), Person.class);
Method setterName = pd.getWriteMethod();
if(setterName!=null){
String value = annotation.value();
filed.setAccessible(true);
setterName.invoke(p, value);
}
}
}
p.sayHello();
}
}
程序运行结果为:zhangsan
这就是通过注解,给属性赋值的过程。