一.
通过Junit4.x深入分析Annotation在框架中的实际应用
在所有方法执行之前执行的方法---@BeforeClasspublic static void a(){}
在所有方法执行之后执行的方法---@AfterClass
public static void b(){}
二.
限定annotation使用对象@Target
表示@Target所修饰的注解是用来修饰什么的(Class Method ......), Target与ElementType是结合使用的
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
//表示@Target所修饰的注解是用来修饰什么的(Class Method ......)
@Target( { ElementType.METHOD, ElementType.TYPE })
public @interface MyTarget {
String value();
}
@MyTarget("hello")
public class MyTargetUsage {
@MyTarget("world")
public void doSomething() {
}
}
三.
Retention与RetentionPolicy是结合使用的
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface InheritedTest {
String value();
}
四.
要求为API文件@Documented
想要在使用者制作JavaDoc文件的同时,也一并将Annotation的讯息加入至API文件中使用java.lang.annotation.Documented
import java.lang.annotation.Documented;
@Documented
public @interface DocumentedAnnotation {
String hello();
}
public class DocumentTest {
/**
* This is comments that I hava added
*/
@DocumentedAnnotation(hello = "welcome")
public void method() {
System.out.println("hello world");
}
}
五.
子类是否继承父类@Inherited
预设上父类别中的Annotation并不会被继承至子类别中,可以在定义Annotation型态时加上。 java.lang.annotation.Inherited型态的Annotation
@InheritedTest("itcast")
public class Parent {
public void doSomething(){
System.out.println("do something");
}
}
public class Child extends Parent {
}
public class Test {
public static void main(String[] args) {
Class<Child> clazz = Child.class;
if(clazz.isAnnotationPresent(InheritedTest.class)){
InheritedTest inheritedTest=clazz.getAnnotation(InheritedTest.class);
String value=inheritedTest.value();
System.out.println(value);
}
}
}
六.
注解与XML
struts2.0中的配置文件,即可以用XML来配置,也可以用注解来配置。(注解应用用于替代xml配置文件)EJB3.0也采用注解来配置
注解又被称为元数据(不能再分割的数据)