Java注解:自定义注解(Annotation)

1、定义注解的关键字:@interface

定义Annotation使用的关键字是:@interface (在原有的interface前增加@符号)

**示例:**自定义的注解

package learn.demo.annotations;

/**
 * 这是自定义的一个简单的 annotation
 * */
public @interface MyAnnotation {
    
    
	// 
}

**使用:**使用自己定义的注解

	@MyAnnotation 
    public void testMyAnnotation(){
    
    
        System.out.println("测试自己定义的注解MyAnnotation");
    }

解释:
在上面的我们定义的Annotation可用于修饰类、接口、方法、成员属性等任何程序元素。

2、在自定的注解中添加属性

注解中我们也可以为注解设置一定的属性,例如我们可以在MyAnnoation注解中加入需要的属性(成员变量)

语法: 类型 属性名()
备注:这里的 () 是必须的

public @interface MyAnnotation {
    
    
	// 添加自己的属性
	String name();
	int age();
}

使用:

	@MyAnnotation(name = "kuyin",age = 18) 
    public void testMyAnnotation(){
    
    
        System.out.println("测试自己定义的注解MyAnnotation,带属性");
    }

3、提取Annotation的信息:

在Java中提供了java.lang.reflect.AnnotateElement接口,该接口代表程序中可以接受注释的程序元素,实现类有:

  • java.lang.reflect.Class:类定义
  • java.lang.reflect.Constructor: 构造器定义
  • java.lang.reflect.Field: 类的成员变量定义
  • java.lang.reflect.Method:类的方法定义
  • java.lang.reflect.Package:类的包定义

主要的方法:

  • Annotation[] getAnnotations():获取该程序元素上的所有注解
  • Annotation[] getDeclaredAnnotations():获取该程序元素上的所有运行时的注解
  • default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass):判断该程序元素上是否包含指定类型的注解,存在返回true,否返回false
package learn.demo.annotations;

import org.junit.Test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings(value = "unchecked")
public class TestAnnotation {
    
    

    /**
     * 测试获取方法 testGetAnnotation() 上的注解
     * */
    @MyAnnotation
    @Deprecated
    @Test
    public void testGetAnnotation()throws Exception{
    
    
        Class<TestAnnotation> thisClass = TestAnnotation.class;
        Method testGetAnnotation = thisClass.getMethod("testGetAnnotation");
        Annotation[] annotations = testGetAnnotation.getDeclaredAnnotations();
        System.out.println("使用到的注解有"+annotations.length +"个:");
        for (Annotation an: annotations){
    
    
            System.out.println(an);
        }
    }

注意:上面的注解只能获取运行时存在的注解,如果不是的话,就无法获取到,如果时要获取到 @MyAnnotation 注解,需要将注解修改为:

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    
    
	// ...
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Hicodden/article/details/110679885