Annotation注解 (一)

Annotation



自定义的Annotation注解:

package com.annotation.java;

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)  //限定 myAnnotation只能用在method方法上。
public @interface myAnnotation {
	String value2() default "zhangsan";
	String value3();
	int in4();
}

@Retention(RetentionPolicy.RUNTIME)
Retation注释可以修饰注释,RetentionPolicy是枚举类型。

Quote From JDK:@Retention Indicates how long annotations with the annotated type are to
 * be retained. @Retention意思是被它修饰的注释保持多久,有三种枚举策略RetentionPolicy可选:CLASS  SOURCE  RUNTIME

这里的RetentionPolicy定义为 RUNTIME类型,表明myAnnotation是记录在Class文件中,并可被JVM在运行期获取,以反射的方式被读取。

@Target(ElementType.METHOD)  //限定 myAnnotation只能用在method方法上。
Target注释表明哪种类型(函数METHOD、构造器CONSTRUCTOR、类/接口/枚举 TYPE)可以被这个Target修饰的注释修饰。

这里ElementType枚举设定为Method ,表明myAnnotation只能修饰函数method。


下面自定义一个类中的一个方法被 myAnnotation修饰。

package com.annotation.java;

import java.util.ArrayList;

import java.util.List;

//@myAnnotation(value3="class",in4=10)

public class UsingMyAnnotation {

	@SuppressWarnings("unchecked") 
	@Deprecated
	@myAnnotation(value3 = "method_print", in4 = 90)
	public void print(String str) {

		List list = new ArrayList();
		System.out.println("method: " + str);
	}
}
可以看出,在print函数上有三个注释修饰,第三个为自定义的@myAnnotation(value3 = "method_print", in4 = 90) 并给其赋值。


下面将利用反射机制来获取该方法print上的Annotation信息。

package com.annotation.java;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class CheckMyAnnotation {

	public static void main(String[] args) throws Exception {

		Class<?> classtype = UsingMyAnnotation.class;//利用反射来获取UsingMyAnnotation类对应的运行中的Class对象
		UsingMyAnnotation objMyAnnotation = (UsingMyAnnotation) classtype 反射来new一个实例
				.newInstance();

		Method methodOfAnnotation = classtype.getMethod("print",
				new Class[] { String.class });  利用反射来获取print方法对应的Method对象 
		if (methodOfAnnotation.isAnnotationPresent(myAnnotation.class)) { //isAnnotationPresent是Method父类AccessibleObject的函数,Feild、Construtor也是

			methodOfAnnotation.invoke(objMyAnnotation,
					new Object[] { "success!" });

			myAnnotation my = methodOfAnnotation
					.getAnnotation(myAnnotation.class);//获取该方法上的myAnnotation注解

			System.out.println(my.value3() + my.in4());
		}
		Annotation[] mys = methodOfAnnotation.getAnnotations();//获取该方法上的的所有RetentionPolicy为RUNTIME的注解
		for (Annotation annotation : mys) {
			System.out.println(annotation.annotationType().getName());

		}
	}
}


打印结果:



注意:打印出java.lang.Deprecated 而没有打印出SuppressWarnings注解,是因为 前者的 是RetentionPolicy.RUNTIME 而后者是:RetentionPolicy.SOURCE

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值