实例:Java注解深入浅出
发布日期:2021-05-08 00:50:51 浏览次数:28 分类:精选文章

本文共 3470 字,大约阅读时间需要 11 分钟。

一,前期基础知识储备

1)Java注解(Annotation)

Java注解是一种元数据机制,用于为代码中的类、方法、变量、参数和包等元素提供额外信息。与类、接口等类似,注解本身也是一个类类型。注解在编译器和运行时都可以发挥作用,但通常用于静态分析或在运行时获取配置信息。

2)Java内置注解

Java提供了多种内置注解,共分为两类:

  • 直接作用于代码的注解:如@Override@Deprecated@SuppressWarnings等。
  • 元注解:用于描述注解本身的属性,包括@Retention@Target@Documented@Inherited@Repeatable等。

3)Annotation组成部分

Java注解的组成部分包括以下三个核心部分:

  • Annotation接口:所有注解都必须实现Annotation接口。
  • ElementType枚举:指定注解作用的目标元素类型,如TYPE(类、接口等)、FIELD(字段)、METHOD(方法)等。
  • RetentionPolicy枚举:指定注解在编译期、字节码期或运行期的保留策略。

4)自定义Annotation

自定义注解的格式如下:

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation {    String name();    int age() default 18;}

注解的关键特点:

  • 使用@interface定义注解类。
  • 可选使用@Documented控制注解是否出现在文档中。
  • 必须指定@Target@Retention,若省略默认值分别为ElementType.NO_TYPERetentionPolicy.CLASS
  • 方法命名为value时可省略@value属性。

二,上代码,具体实现

1)获取注解属性

通过反射机制可以获取注解信息。Class类提供了多种方法:

  • getAnnotation(Annotation annotationClass):获取指定注解类的注解。
  • isAnnotationPresent(Annotation annotationClass):判断元素是否有指定注解。
  • getDeclaredAnnotationgetDeclaredAnnotations:获取本元素的注解,不包含继承的。

2)自定义注解应用

@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface SxtFiled {    String columnName();    String type();    int length();}@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface SxtTable {    String value();}@SxtTable("tb_table")public class SxtStudent {    @SxtFiled(columnName = "id", type = "int", length = 10)    private int id;    @SxtFiled(columnName = "sname", type = "varchar", length = 10)    private String studentName;    @SxtFiled(columnName = "age", type = "int", length = 3)    private int age;}

3)反射获取注解

Class
studentClass = SxtStudent.class;Annotation[] annotations = studentClass.getAnnotations();SxtTable sxtTable = studentClass.getAnnotation(SxtTable.class);SxtFiled sxtField = studentClass.getDeclaredField("studentName").getAnnotation(SxtFiled.class);if (sxtTable != null) { System.out.println("表名:" + sxtTable.value());}if (sxtField != null) { System.out.println("字段名:" + sxtField.columnName()); System.out.println("字段类型:" + sxtField.type()); System.out.println("字段长度:" + sxtField.length());}

三,实例,使用注解进行参数配置

BankTransferMoney注解

@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface BankTransferMoney {    double maxMoney() default 10000;}public class BankService {    @BankTransferMoney(maxMoney = 15000)    public static void transferMoney(double money) {        System.out.println(processAnnotationMoney(money));    }    private static String processAnnotationMoney(double money) {        try {            Method transferMethod = BankService.class.getDeclaredMethod("transferMoney", double.class);            if (!transferMethod.isAnnotationPresent(BankTransferMoney.class)) {                return "无有效注解";            }            BankTransferMoney annotation = transferMethod.getAnnotation(BankTransferMoney.class);            double limit = annotation.maxMoney();            if (money > limit) {                return "转账金额超过限额,转账失败";            } else {                return "转账金额为:" + money + ",转账成功";            }        } catch (NoSuchMethodException e) {            e.printStackTrace();        }        return "转账处理失败";    }    public static void main(String[] args) {        transferMoney(10000);    }}

通过上述例子,可以看到注解在参数配置中的实际应用,开发者无需修改源代码即可动态调整配置值。

注解的作用

注解在开发中具有重要作用:

  • 提供元数据,辅助编译器检查和处理。
  • 在运行时供反射获取,实现动态配置和行为改变。
  • 第三方框架如ButterKnife、Retrofit等广泛应用注解技术,简化代码编写和维护。

注解处理工具(APT)可以自动解析和处理注解信息,提升开发效率。

上一篇:并发编程:线程的共享与协作
下一篇:实例:Gson解析泛型对象

发表评论

最新留言

关注你微信了!
[***.104.42.241]2025年04月09日 03时17分37秒