java annotation 是java5之后引入的。主要包括三种标准注解:
@Override:覆盖超类中的方法。
@Deprecated:表示不推荐,可以用来表示一些将要在未来版本被废弃的方法。
@SuppressWarnings:关闭不当的编译器表示信息。
除了三种标准注解外,还有四种元注解。
@Target 表示注解的作用范围。可能的ElementType包括:CONSTRUCTOR(构造器的声明),FIELD(域声明),LOCAL_VARIABLE(局部变量的声明)、METHOD(方法声明)。PAKAGE(包声明)、PARAMETER(参数声明)、TYPE(类、接口、注解或者是Enum的声明)。其中相对来说Method和field更常用。
@Retention: 表示注解保存的级别。可选的RetentionPolicy包括: SOURCE(注解将被编译器丢掉,也就是class文件中不存在),CLASS(注解在class文件中可用,但会被vm丢掉),RUNTIME(VM在运行其也将保留这些注解,可以通过反射读取注解的信息)。
@Documented 将注解包含在javadoc中。
@Inherited 允许子类继承父类的注解。
下面看一个annotation的示例:
Annotation的定义:
package annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationDemo {
String check() default "hello world!";
}
Annotation的处理器:
package annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class AnnotationDemoInterceptor {
public void checkInterceptor(Class<?>cl){
for(Method m :cl.getDeclaredMethods()){
AnnotationDemo annoDemo = m.getAnnotation(AnnotationDemo.class);
if(annoDemo !=null){
System.out.println("Found AnnotationDemo in "+m.getName()+" :"+annoDemo.check());
}else{
System.out.println("Found nothing in "+m.getName());
}
}
}
}
测试类:
package annotation;
public class AnnotationDemoTest {
public static void main(String[]args){
AnnotationDemoInterceptor adi = new AnnotationDemoInterceptor();
adi.checkInterceptor(AnnotationDemoTest.class);
}
@AnnotationDemo(check = "hello, shuofenglxy")
public static void doSomething(){
System.out.println("This is an annotation example!");
}
@AnnotationDemo()
public static void doHello(){
System.out.println("This is an annotation example!");
}
public static void doOtherthing(){
System.out.println("This is normal method!");
}
}
测试结果:
Found AnnotationDemo in doSomething :hello, shuofenglxy
Found AnnotationDemo in doHello :hello world!
Found nothing in doOtherthing
Found nothing in main
说明:通过这个简单的示例,大概说明了自己书写annotation的过程,在spring,ejb中大量应用了annotation,原理也是大致相同的,无非定义annotation,设置处理器,然后就可以用了。在自己的应用中可以用annotation的方式来做权限管理等等。