温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

关于Java Annotation注解相关原理的案例

发布时间:2020-07-08 11:22:17 来源:亿速云 阅读:132 作者:清晨 栏目:开发技术

小编给大家分享一下关于Java Annotation注解相关原理的案例,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

Java.lang 中自带的注解

  • @Override:表示当前的方法定义将覆盖基类的方法。如果你不小心拼写错误,或者方法签名被错误拼写的时候,编译器就会发出错误提示。
  • @Deprecated:如果使用该注解的元素被调用,编译器就会发出警告信息。
  • @SuppressWarnings:关闭不当的编译器警告信息。
  • @SafeVarargs:在 Java 7 中加入用于禁止对具有泛型varargs参数的方法或构造函数的调用方发出警告。
  • @FunctionalInterface:Java 8 中加入用于表示类型声明为函数式接口

如何定义注解

以下是一个为标记注解(marker annotation), 不包含任何元素

package cn.haidnor.annotation;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
  
}

注解的定义也需要一些元注解(meta-annoation),比如 @Target 和 @Retention。

@Target 定义你的注解可以应用在哪里(例如是方法还是字段)。

@Retention 定义了注解在哪里可用,在源代码中(SOURCE),class文件(CLASS)中或者是在运行时(RUNTIME)。

Demo 简单实例

定义注解

以下的代码中。Target 定义只能在方法上使用,Retention 定义保留域

package cn.haidnor.annotation;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UseCase {
  int id();
  String description() default "no description";
}

在类中使用注解

package cn.haidnor.clazz;
package cn.haidnor.clazz;
import cn.haidnor.annotation.UseCase;
import java.util.List;

public class PasswordUtils {
  @UseCase(id = 47, description ="Passwords must contain at least one numeric")
  public boolean validatePassword(String passwd) {
    return (passwd.matches("\\w*\\d\\w*"));
  }
  @UseCase(id = 48)
  public String encryptPassword(String passwd) {
    return new StringBuilder(passwd)
        .reverse().toString();
  }
  @UseCase(id = 49, description = "New passwords can't equal previously used ones")
  public boolean checkForNewPassword(
      List<String> prevPasswords, String passwd) {
    return !prevPasswords.contains(passwd);
  }
}

对以上 demo 中的代码进行测试

package cn.haidnor.test;

import cn.haidnor.annotation.UseCase;
import cn.haidnor.clazz.PasswordUtils;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.*;
import java.lang.reflect.*;

public class UseCaseTracker {

  public static void main(String[] args) {
    List<Integer> useCases = IntStream.range(44, 51)
        .boxed().collect(Collectors.toList());
    trackUseCases(useCases, PasswordUtils.class);
  }

  public static void trackUseCases(List<Integer> useCasesList, Class<&#63;> clazz) {
    // getDeclaredMethods() 获取所有公开的方法
    for(Method m : clazz.getDeclaredMethods()) {
      // getAnnotation() 获取指定注解
      UseCase uc = m.getAnnotation(UseCase.class);
      if(uc != null) {
        System.out.print("Found Use Case ");
        // 提取注解元素值
        System.out.println(uc.id());
        // 提取注解元素值
        System.out.println('\t' + uc.description());
        useCasesList.remove( Integer.valueOf( uc.id() ) );
      }
    }

    // 迭代集合
    useCasesList.forEach(new Consumer<Integer>() {
      @Override
      public void accept(Integer integer) {
        System.out.println("Missing use case " + integer);
      }
    });
    // 以上代码可以使用箭头行数简写
    // useCasesList.forEach(i -> System.out.println("Missing use case " + i));
  }
}

控制台输出结果

Found Use Case 47
  Passwords must contain at least one numeric
Found Use Case 48
  no description
Found Use Case 49
  New passwords can't equal previously used ones
Missing use case 44
Missing use case 45
Missing use case 46
Missing use case 50

元注解

Java 语言中目前有 5 种标准注解(前面介绍过),以及 5 种元注解。元注解用于注解其他的注解

关于Java Annotation注解相关原理的案例

注解中可以使用的元素

所有基本类型(int、float、boolean等)

  • String
  • Class
  • enum
  • Annotation
  • 以上类型的数组

其他类型,编译器就会报错。注意,也不允许使用任何包装类型

  • 注解的默认值
     

无论是在源代码声明时还是在注解接口中定义默认值时,都不能使用 null 作为其值。

import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SimulatingNull {
  int id() default -1;
  String description() default "";
}

使用反射获取注解的方法流程图

关于Java Annotation注解相关原理的案例

看完了这篇文章,相信你对关于Java Annotation注解相关原理的案例有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI