1. java annotation是什么?有什么作用?
自从java 1.5(代号tiger,1.6代号为mustang)引入annotation以后,java annontation就被广泛的使用了,很多java框架也紧跟潮流,例如Junit、Struts、Spring等流行工具框架中均广泛使用了annontion。 Spring 2.5提供了完全基于注释配置 Bean、装配 Bean 的功能,您可以使用基于注释的 Spring IoC 替换原来基于 XML 的配置.
Annotation语法,除了@符号的使用外,它基本上与java的固有语法一致,java内置了三种注解,定义在java.lang.annotation包。
Annotation可以被编译为近class文件的,也可以在运行时被虚拟机获得,从而影响运行时行为。
Annotation一般作为一种辅助途径,应用在软件框架或工具中,在这些工具类中根据不同的 annontation注解信息采取不同的处理过程或改变相应程序元素(类、方法及成员变量等)的行为
2.如何自定义annotation?
自定义annotation
package annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
public String value() default "hello annotation";
}
测试annotation
package annotation;
import java.lang.reflect.Method;
public class TestAnno {
@MyAnnotation(value = "I am annotation for method_1")
public static void method_1(){
System.out.println("I am method_1");
}
@MyAnnotation()
public static void method_2(){
System.out.println("I am method_2");
}
public static void main(String[] args) {
method_1();
method_2();
// 利用反射机制得到方法的annotation
Method[] methods = TestAnno.class.getDeclaredMethods();
for(Method method : methods ){
boolean hasAnnotation = method.isAnnotationPresent(MyAnnotation.class);
if(hasAnnotation){
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
System.out.println("metod: " + method.getName() + " ; annotation content: " + annotation.toString() + " annotation value:" + annotation.value());
}
}
}
}