第二十二:Java Annotation(下)

一.

通过Junit4.x深入分析Annotation在框架中的实际应用

在所有方法执行之前执行的方法---@BeforeClass
public 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也采用注解来配置
注解又被称为元数据(不能再分割的数据)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值