Java注解:元注解、普通注解、组合注解

一、自定义注解

@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Info {

      String value() default "tracy";

      boolean isDelete();
}

// 为Person类配置了刚刚定义的注解@Info
@Info(isDelete = true)
public class Person {

    // 姓名
    private String name;

    // 年龄
    private int age;

    // 是否有效
    private boolean isDelete;
}

利用反射解析注解


public class AnnotationTest {
    public static void main(String[] args) {
        try {
            //获取Person的Class对象
            Person person = Person.builder().build();
            Class clazz = person.getClass();
            //判断person对象上是否有Info注解
            if (clazz.isAnnotationPresent(Info.class)) {
                System.out.println("Person类上配置了Info注解!");
                //获取该对象上Info类型的注解
                Info infoAnno = (Info) clazz.getAnnotation(Info.class);
                System.out.println("person.name :" + infoAnno.value() + ",person.isDelete:" + infoAnno.isDelete());
            } else {
                System.out.println("Person类上没有配置Info注解!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在这里插入图片描述

二、元注解

元注解是java API提供,是专门用来定义注解的注解。

元注解共有四个,分别是:

  1. @Target
  2. @Retention
  3. @Documented
  4. @Inherited 

2.1 @Target

用于描述注解的范围。

取值示例:@Target(value=ElementType.TYPE)或者@Target(value={ElementType.METHOD,ELementType.TYPE}))

总共有以下几种取值:

2.2 @Retention

表示需要在什么级别保存该注释信息,用于描述注解的生命周期。

2.3 @Documented

用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。

Documented是一个标记注解,没有成员。

2.4 @Inherited

@Inherited阐述了某个被标注的类型是被继承的。

如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。

@Inherited 元注解是一个标记注解

三、组合注解

组合注解:将多个注解组合到一块生成一个新的注解。使用这个新的注解就相当于使用了该组合注解中所有的注解。

3.1 创建组合注解

通过一个简单的实例来看一下如何将多个注解组合到一块。

Spring配置类中,我们经常使用到@Configuration和@ComponentScan这两个注解,接下来,我们将其进行组合封装,从而形成一个新的注解。


import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
@ComponentScan
public @interface CombinationConfiguration {
    String[] value() default{};
}

@CombinationConfiguration注解兼有@Configuration和@ComponentScan这两个注解的功能。

3.2 组合注解的使用

创建完相应的组合注解后就到了使用的时候了,上面注解的使用和一般的注解没有什么区别。只是这个注解表示之前写的@Configuration和@ComponentScan这两个注解。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值