java自定义注解实例

1、创建注解;(至于Retention,Target,Documented的含义自行学习)

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)		// VM将在运行期保留注释,因此可以通过反射机制读取注解的信息
@Target(ElementType.TYPE)		// 表示注解类型,TYPE为类,接口,枚举的声明
@Documented		// 表示此注解将包含在javadoc中
public @interface TypeAnnotation {
	/** 类名 */
	String ClassName();
	/** 描述 */
	String Description();
	/** 作者 */
	String author();
	/** 创建日期 */
	String date();
}

2、测试类及方法;

import com.annotation.TypeAnnotation;

@TypeAnnotation (ClassName="AnnotationTest", Description = "测试自定义类注解", author = "rencht", date = "2013-4-8 上午10:07:54")
public class AnnotationTest {

	public static void main(String[] args) throws Exception {
		AnnotationTest test = new AnnotationTest();
		
		TypeAnnotation annotation = test.getClass().getAnnotation(TypeAnnotation.class);
		System.out.println(annotation.ClassName());
		System.out.println(annotation.Description());
		System.out.println(annotation.author());
		System.out.println(annotation.date());

	}
}

3、输出结果;

AnnotationTest
测试自定义类注解
rencht
2013-4-8 上午10:07:54


Tips:

1、由于使用反射机制取得注解,注解类型为局部变量LOCAL_VARIABLE时无法取得,那该类型注解的意义何在?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值