zoukankan      html  css  js  c++  java
  • Java 注解

    元信息

    Java 注解(Annotation)又称 Java 标注,是 JDK5.0 引入的一种注释机制。

    Java 语言中的类、方法、变量、参数和包等都可以被标注。和 Javadoc 不同,Java 标注可以通过反射获取标注内容。在编译器生成类文件时,标注可以被嵌入到字节码中。Java 虚拟机可以保留标注内容,在运行时可以获取到标注内容 。 当然它也支持自定义 Java 标注。

    由于jdk和框架大量使用注解,我也简单介绍下注解为何物,若您发现文章中存在错误或不足的地方,希望您能指出!

    Java 定义了一套注解,共有 7 个,3 个在 java.lang 中,剩下 4 个在 java.lang.annotation 中。

    作用在代码的注解是

    • @Override - 检查该方法是否是重写方法。如果发现其父类,或者是引用的接口中并没有该方法时,会报编译错误。
    • @Deprecated - 标记过时方法。如果使用该方法,会报编译警告。
    • @SuppressWarnings - 指示编译器去忽略注解中声明的警告。

    作用在其他注解的注解(或者说 元注解)是:

    • @Retention - 标识这个注解怎么保存,是只在代码中,还是编入class文件中,或者是在运行时可以通过反射访问。
    • @Documented - 标记这些注解是否包含在用户文档中。
    • @Target - 标记这个注解应该是哪种 Java 成员。
    • @Inherited - 标记这个注解是继承于哪个注解类(默认 注解并没有继承于任何子类)

    从 Java 7 开始,额外添加了 3 个注解:

    • @SafeVarargs - Java 7 开始支持,忽略任何使用参数为泛型变量的方法或构造函数调用产生的警告。
    • @FunctionalInterface - Java 8 开始支持,标识一个匿名函数或函数式接口。
    • @Repeatable - Java 8 开始支持,标识某注解可以在同一个声明上使用多次。

     

    Annotation 架构图如下:

    Annotation 的每一个实现类,都 和 1 个 RetentionPolicy 关联, 和 1~n 个 ElementType 关联。

    注意RetentionPolicy的三种策略,自定义注解需要设置策略

    public enum RetentionPolicy {
        /**
         * Annotations are to be discarded by the compiler.
           注解将被编译器丢弃
         */
        SOURCE,
    
        /**
         * Annotations are to be recorded in the class file by the compiler
         * but need not be retained by the VM at run time.  This is the default
         * behavior.
           注解在class文件中可用,但会被VM丢弃
         */
        CLASS,
    
        /**
         * Annotations are to be recorded in the class file by the compiler and
         * retained by the VM at run time, so they may be read reflectively.
         *  VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息
         * @see java.lang.reflect.AnnotatedElement 
         */
        RUNTIME
    }

    注意ElementType,自定义注解时特别关注,有多种类型

    public enum ElementType {
        /** Class, interface (including annotation type), or enum declaration 
            类,接口(包括注解类型)或enum声明*/
        TYPE,
    
        /** Field declaration (includes enum constants) 
            域声明(包括 enum 实例)*/
        FIELD,
    
        /** Method declaration 方法声明*/
        METHOD,
    
        /** Formal parameter declaration 参数声明*/
        PARAMETER,
    
        /** Constructor declaration 构造器声明*/
        CONSTRUCTOR,
    
        /** Local variable declaration 局部变量声明*/
        LOCAL_VARIABLE,
    
        /** Annotation type declaration 注解类型声明*/
        ANNOTATION_TYPE,
    
        /** Package declaration 包声明*/
        PACKAGE,
    
        /**
         * Type parameter declaration
         *
         * @since 1.8
         */
        TYPE_PARAMETER,
    
        /**
         * Use of a type
         *
         * @since 1.8
         */
        TYPE_USE
    }
    

    下面是个小例子:

    自定义注解:

    @Documented
    @Target({ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
    @Inherited
    @Retention(RetentionPolicy.RUNTIME)
    public @interface CustomAnnotation {
    
    	public String name() default "";
    	public String value() default "";
    }
    

     在类中使用

    /**
     * @author dgm
     * @describe ""
     */
    @CustomAnnotation(name="Class Annotation",  value = " 类上的注解")
    public class SampleClass {
    	@CustomAnnotation(name = "field Annotation", value = "字段上的注解")
    	public String sampleField;
    
    	@CustomAnnotation(name = "constructor  Annotation", value = "构造器上的注解")
    	public SampleClass(String sampleField) {
    		super();
    		this.sampleField = sampleField;
    	}
    
    	@CustomAnnotation(name = "Method Annotation getSampleField", value = "getSampleField无参方法上的注解")
    	public String getSampleField() {
    		System.out.println("getSampleField");
    		return sampleField;
    	}
    
    	@CustomAnnotation(name = "Method Annotation setSampleField", value = "setSampleField方法上的注解")
    	public void setSampleField(String sampleField) {
    		System.out.println("setSampleField=" + sampleField);
    		this.sampleField = sampleField;
    	}
    
    	@CustomAnnotation(name = "Method Annotation getSampleField hava param", value = "getSampleField有参方法上的注解")
    	private String getSampleField(String sampleField) {
    		return sampleField;
    	}
    }

    测试类

    /**
     * 
     * @author dgm
     * @describe ""
     */
    public class CustomAnnotationTest {
    
    	 public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    		Class c0 = SampleClass.class;
    		Class c1 = Class.forName("spring.annotation.SampleClass");
    		Object o = null;
    		try {
    			o = Class.forName("spring.annotation.SampleClass").getConstructor(String.class).newInstance("dongguangming");
    		} catch (NoSuchMethodException | SecurityException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		Class c2 = o.getClass();
    		System.out.println(c0 == c1);
    		System.out.println(c0 == c2);
    		System.out.println(c1 == c2);
    
    		// 获取类的所有注解
    		Annotation[] classAnnotation = c0.getAnnotations();
    		for (Annotation ca : classAnnotation) {
    			if (ca instanceof CustomAnnotation) {
    				CustomAnnotation customAnnotation = (CustomAnnotation) ca;
    				System.out.println("class name: " + customAnnotation.name());
    				System.out.println("class value: " + customAnnotation.value());
    			}
    		}
    
    		// 获取类的公有field
    		Field[] fields = c0.getFields();
    		for (Field field : fields) {
    			Annotation[] fieldAnnotation = field.getAnnotations();
    			for (Annotation fa : fieldAnnotation) {
    				if (fa instanceof CustomAnnotation) {
    					CustomAnnotation customAnnotation = (CustomAnnotation) fa;
    					System.out
    							.println("field name: " + customAnnotation.name());
    					System.out.println("field value: "
    							+ customAnnotation.value());
    
    				}
    			}
    		}
    
    		// 获取构造器的所有注解
    		// 获取类的构造器
    	    Constructor<?>[] publicConstructors = c0.getConstructors();//getDeclaredConstructors
    
    	    for (Constructor constructor : publicConstructors) {
    			Annotation[] methodAnnotation = constructor.getAnnotations();
    			for (Annotation ma : methodAnnotation) {
    				if (ma instanceof CustomAnnotation) {
    					CustomAnnotation customAnnotation = (CustomAnnotation) ma;
    					System.out.println("构造器 name: "
    							+ customAnnotation.name());
    					System.out.println("构造器 value: "
    							+ customAnnotation.value());
    
    				}
    			}
    	    }
    	    
    		// 获取类的公有方法
    		Method[] methods = c0.getMethods();
    		// Annotation annotation =
    		// methods[1].getAnnotation(CustomAnnotation.class);
    		for (Method method : methods) {
    			Annotation[] methodAnnotation = method.getAnnotations();
    			for (Annotation ma : methodAnnotation) {
    				if (ma instanceof CustomAnnotation) {
    					CustomAnnotation customAnnotation = (CustomAnnotation) ma;
    					System.out.println("method name: "
    							+ customAnnotation.name());
    					System.out.println("method value: "
    							+ customAnnotation.value());
    
    				}
    			}
     // 获取方法上的所有参数注解 
                Annotation[][] parameterAnnotations = method.getParameterAnnotations();
                for(Annotation[] pa : parameterAnnotations){
                    for(Annotation a:pa){
                        if(a instanceof CustomAnnotation){
                            System.out.println("method param name: "
        							+ ((CustomAnnotation) a).name());
        					System.out.println("method param value: "
        							+ ((CustomAnnotation) a).value());
                        }
                    }
                }
    
    		}
    	   }
    }

    执行效果:

     看到了吧,一个类上可以多个注解,一个字段也可以有多个注解,构造器上也可以多个注解,方法上也可以有多个注解、参数上也可以有多个注解,而类是可以有多个字段、多个构造器(每个构造器都可能有多个参数)、多个方法(每个方法也都肯能有多个参数)),所以真正写框架时光逻辑性if else判断就折腾 了。。。举个例子类上有A注解执行什么代码,有B注解执行什么代码,以此类推字段、构造器、方法、参数的多个注解的处理过程。

     

    实际开发中我们也会用到自定义注解,比如:

    自定义注解是很强大的功能,广泛应用于框架(Struts,hibernate,Mybatis,Spring,  Spring boot,sping cloud,dubbo等)和系统开发公共模块(比如上图中的登录拦截和取当前用户)中

    参考:

    0. Java程序员必须掌握的5个注解! https://developer.51cto.com/art/201807/577539.htm

    1. Lesson: Annotations

    https://docs.oracle.com/javase/tutorial/java/annotations/

    2. Java Annotations Tutorial https://www.javacodegeeks.com/2014/11/java-annotations-tutorial.html

    3. How To Process Java Annotations

    https://www.javacodegeeks.com/2015/01/how-to-process-java-annotations.html

    4. An introductory guide to annotations and annotation processors 

    https://blog.frankel.ch/introductory-guide-annotation-processor/

    5. Java Annotation Processing and Creating a Builder
    https://www.baeldung.com/java-annotation-processing-builder

    6. How and when to use Enums and Annotations https://www.javacodegeeks.com/2015/09/how-and-when-to-use-enums-and-annotations.html

    7. Common Annotations for the Java™ Platform™ https://download.oracle.com/otn-pub/jcp/common_annotations-1_3-mrel3-eval-spec/jsr-250.pdf?AuthParam=1590270326_b56b01b1aeacddec8562720c1b2f27b8

    8. Java - Understanding @Inherited meta annotation

    https://www.logicbig.com/tutorials/core-java-tutorial/annotations/inherited-meta-annotation.html

    9. 深入理解java注解的实现原理 https://mp.weixin.qq.com/s?__biz=MzAxMjY1NTIxNA==&mid=2454441897&idx=1&sn=729688d470c94560c1e73e79f0c13adc&chksm=8c11e0a8bb6669be1cc4daee95b221ba437d536d598520d635fac4f18612dded58d6fddb0dce&scene=21#wechat_redirect

    10.  Annotations in Java 5.0  https://javabeat.net/annotations-in-java-5-0/

  • 相关阅读:
    c++之类模板
    c++之函数模板
    c++之继承三
    c++之继承二
    c++之继承一
    c++之类类型转换
    c++之运算符重载二
    c++之运算符重载一
    Mahout学习路线路
    数据库分区
  • 原文地址:https://www.cnblogs.com/dongguangming/p/12953801.html
Copyright © 2011-2022 走看看