Annotation注解 (一)

来源:互联网 发布:网络知识竞赛的网址 编辑:程序博客网 时间:2024/04/28 09:27

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

0 0