java注解是java语言的一个有利补充,尤其是在各种框架中,注解应用极为频繁。
java中内置的标准注解有3个,@Override用于方法重载,@Depcreted用于声明方法为不推荐使用、@SuppressWarning用于忽略警告。
当需要自定义注解时用到元注解,共有4个,@Target、@Retention、@Documented、@Inherited
@Target声明了注解的应用范围,ElementType有CONSTRUCTOR、FIELD、METHOD、TYPE、PACKAGE、PARAMETER、LOCAL_VARIABLE。
@Retention声明了注解的作用范围,RetentionPolicy有SOURCE、CLASS、RUNTIME。
@Documented将此注解包含在JavaDoc中。
@Inherited允许子类继承父类的注解,但是需要注意的是注解不能被继承。
一个简单的注解定义例子
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value=ElementType.METHOD) // 声明该注解的应用对象是方法
@Retention(value=RetentionPolicy.RUNTIME) // 声明该注解在运行时也有效,即在JVM中生效
public @interface Description {
public long id = -1;
public String name = "";
}
一个简单的使用注解的例子
// 使用注解Description
public class AnnotationUseCase {
@Description(id=1, name="A")
public void descriptionA(){
System.out.println("descriptionA");
}
@Description(name="B")
public void descriptionB(){
System.out.println("descriptionB");
}
}
一个简单的处理注解的例子
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
// 处理注解
Class cl = Class.forName("ownjava.in.think.chapter20.AnnotationUseCase");
for(Method method : cl.getDeclaredMethods()){
if(method.getDeclaredAnnotations()[0] instanceof Description){
Description description = method.getAnnotation(Description.class);
System.out.println(method.getName() + " id: " +description.id() + " name: " + description.name());
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/* output
descriptionA id: 1 name: A
descriptionB id: -1 name: B
*/