Java—JDK8新特性—重复注解

目录

重复注解是什么?

常见的重复注解的应用场景

源码(JDK中哪里?)

在实际开发中哪里使用了注解(举例)

使用步骤

案例


重复注解是什么?

        重复注解,一个注解可以在一个类、方法、字段上同时使用多次

        重复注解的主要应用场景是对同一个元素可以多次使用同一个注解。这种情况下,我们可以使用重复注解来简化代码,提高可读性

常见的重复注解的应用场景

        1.参数校验:重复注解可以用于对方法参数进行校验

        例如,可以定义一个 @NotNull 注解来标记非空的参数,并且可以重复使用该注解来标记多个参数

public void someMethod(@NotNull String param1, @NotNull String param2) {
    // 方法体
}

        2.权限控制:重复注解可以用于标记访问权限

        例如,可以定义一个 @Role 注解来标记用户角色,并且可以重复使用该注解来为某个方法或类指定多个角色

@Role("admin")
@Role("manager")
public void someMethod() {
    // 方法体
}

        3.日志记录:重复注解可以用于标记日志级别

        例如,可以定义一个 @LogLevel 注解来指定日志级别,并且可以重复使用该注解来记录不同级别的日志。

@LogLevel(LogLevel.INFO)
@LogLevel(LogLevel.ERROR)
public void someMethod() {
    // 方法体
}


源码(JDK中哪里?)

        Module java.base

        Package java.lang.annotation

        Annotation Interface Repeatable

package java.lang.annotation;

/**
 * The annotation interface {@code java.lang.annotation.Repeatable} is
 * used to indicate that the annotation interface whose declaration it
 * (meta-)annotates is <em>repeatable</em>. The value of
 * {@code @Repeatable} indicates the <em>containing annotation
 * interface</em> for the repeatable annotation interface.
 *
 * @since 1.8
 * @jls 9.6.3 Repeatable Annotation Interfaces
 * @jls 9.7.5 Multiple Annotations of the Same Interface
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Repeatable {
    /**
     * Indicates the <em>containing annotation interface</em> for the
     * repeatable annotation interface.
     * @return the containing annotation interface
     */
    Class<? extends Annotation> value();
}
package java.lang.annotation;

@Documented      
@Retention(RetentionPolicy.RUNTIME) //这个生命周期都有效
@Target(ElementType.ANNOTATION_TYPE)  // 作用注解之上
public @interface Repeatable {
    /**
     * Indicates the <em>containing annotation interface</em> for the
     * repeatable annotation interface.
     * @return the containing annotation interface
     */
    Class<? extends Annotation> value();
}


在实际开发中哪里使用了注解(举例)

如Spring中可以使用多个扫描组件来扫描多个包的注解

/
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.context.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.core.annotation.AliasFor;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan {
}


使用步骤

01.定义原始注解

02.定义包装注解

03.使用@Repeatable 注解将原始注解 进行包装

04.使用原始注解


案例

01.定义原始注解@Role

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Role {
    String value();
}

02.定义包装注解@Roles

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Roles {
    Role[] value();
}

03.使用@Repeatable 注解将@Role 进行包装

@Repeatable(包装注解.class)

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Repeatable(Roles.class) // 使用@Repeatable 注解将 @Role 进行包装
public @interface Role {
    String value();
}

04.使用原始注解,创建UserManager类,创建两个方法createUser()和deleteUser()

public class UserManager {

    @Role("admin1")
    @Role("admin2")
    @Role("admin3")
    @Role("admin4")
    @Role("admin5")
    @Role("admin6")
    public void createUser(String username,String password) {
        System.out.println("User created:" + username);
    }

    @Role("root1")
    @Role("root2")
    @Role("root3")
    @Role("root4")
    @Role("root5")
    @Role("root6")
    public void deleteUser(String username) {
        System.out.println("User deleted:" + username);
    }
}

05.测试类

public class TestDemo {
    public static void main(String[] args) throws Exception{
        UserManager userManager = new UserManager();

        Method createUser = UserManager.class.getMethod("createUser", String.class, String.class);
        Role[] roles = createUser.getAnnotationsByType(Role.class);

        for (Role role : roles) {
            System.out.println("create User Role:" + role.value());
        }
        
        userManager.createUser("Jack","123456");

        Method deleteUser = UserManager.class.getMethod("deleteUser", String.class);
        Role[] DeleteUserRoles = deleteUser.getAnnotationsByType(Role.class);
        for (Role role : DeleteUserRoles) {
            System.out.println("Delete User Role:" + role.value());
        }
        userManager.deleteUser("Jack");
    }
}

输出结果:

create User Role:admin1
create User Role:admin2
create User Role:admin3
create User Role:admin4
create User Role:admin5
create User Role:admin6
User created:Jack
Delete User Role:root1
Delete User Role:root2
Delete User Role:root3
Delete User Role:root4
Delete User Role:root5
Delete User Role:root6
User deleted:Jack
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值