如何自定义注解类

如何自定义注解类?


 1 package cn.gacl.annotation;
 2 import java.lang.annotation.ElementType;
 3 import java.lang.annotation.Retention;
 4 import java.lang.annotation.RetentionPolicy;
 5 import java.lang.annotation.Target;
 6 /**
 7  * 这是一个自定义的注解(Annotation)类 在定义注解(Annotation)类时使用了另一个注解类Retention
 8  * 在注解类上使用另一个注解类,那么被使用的注解类就称为元注解
 9  * 
10  * @author 哈哈哈
11  * 
12  */
13 @Retention(RetentionPolicy.RUNTIME)
14 //Retention注解决定MyAnnotation注解的生命周期
15 @Target( { ElementType.METHOD, ElementType.TYPE })
16 //Target注解决定MyAnnotation注解可以加在哪些成分上,如加在类身上,或者属性身上,或者方法身上等成分
17 /*
18  * @Retention(RetentionPolicy.SOURCE)
19  * 这个注解的意思是让MyAnnotation注解只在java源文件中存在,编译成.class文件后注解就不存在了
20  * @Retention(RetentionPolicy.CLASS)
21  * 这个注解的意思是让MyAnnotation注解在java源文件(.java文件)中存在,编译成.class文件后注解也还存在,
22  * 被MyAnnotation注解类标识的类被类加载器加载到内存中后MyAnnotation注解就不存在了
23  */
24 /*
25  * 这里是在注解类MyAnnotation上使用另一个注解类,这里的Retention称为元注解。
26  * Retention注解括号中的"RetentionPolicy.RUNTIME"意思是让MyAnnotation这个注解的生命周期一直程序运行时都存在
27  */
28 public @interface MyAnnotation {
29 }

如何为注解类添加和应用属性?


@Documented
@Retention(value=RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.TYPE })
public @interface MyAnnotation {
	String sayHello() default "hello";
}

怎么使用?

import java.lang.annotation.Annotation;

@MyAnnotation(value="ddd")
public class Main {

	public static void main(String[] args) {
		
		// 检查类AnnotationTest是否含有@MyAnnotation注解
		if (Main.class.isAnnotationPresent(MyAnnotation.class)) {
				MyAnnotation a = (MyAnnotation)Main.class.getAnnotation(MyAnnotation.class);
				System.out.println(a.value()); // 输出:ddd
		}    
//		
	}
}

可以将注解类看做一个接口,default “hello” 指定了默认值。
转至大神:https://blog.youkuaiyun.com/dongbaoming/article/details/70186352的帖子,膜拜中---

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值