• Scala学习笔记16: 注解


    第十六章 注解

    Scala 中的注解 (Annotations) 是一种元编程工具, 用于向编译器、运行时或其他工具提供元数据 ;

    注解可以应用于各种程序结构, 包括类、对象、方法、字段、参数等 ;

    下面是对Scala注解的详细介绍, 包括常见的注解、如何定义自定义注解, 以及使用注解的一些示例 ;

    1- 常见的Scala注解

    1.1 标准注解
    • @deprecated: 标记某个代码元素为过时 ;

    • // 标记某个代码元素为过时
      @deprecated("This method is deprecated, use another method instead", "1.0")
      def oldMethod(): Unit = {
        println("This is an old method")
      }
      
    • @unchecked: 忽略某些编译器警告, 例如模式匹配中的警告 ;

    •     val x: Any = "Hello"
          val y = x match {
            case _: Int => "Integer"
            case _@unchecked => "Other"
          }
          println(y) // Output: Other
      
    • @tailrec: 确保方法是尾递归的, 否则编译器会报错

    • import scala.annotation.tailrec
      
        @tailrec
        def factorial(n: Int, acc: Int = 1): Int = {
          if (n <= 0) acc
          else factorial(n - 1, acc * n)
        }
      
    • @volatile: 标记某个变量为可变变量, 确保在多线程环境下, 变量在每个线程中都有一份独立的拷贝

    • @volatile var count: Int = 0
      
    • @SerialVersionUID: 指定序列化版本号, 确保反序列化时, 使用正确的版本号

    •     @SerialVersionUID(1L)
          class Person(val name: String, val age: Int) extends Serializable
      
    1.2 Java注释

    Scala 也支持 Java 注释, 可以直接在 Scala 代码中使用 Java 注释 ;

    示例 :

    import com.sun.istack.internal.Nullable
    
      def main(args: Array[String]): Unit = {
        // java 注释
        class Example {
          def method(@Nullable param: String): Unit = {
            println(param)
          }
        }
    
        val example = new Example()
        example.method(null) // Output: null
        example.method("Hello") // Output: Hello
      }
    

    2- 自定义注解

    你可以通过定义类并扩展 scala.annotation.Annotation 来创建自定义注解 ;

    import scala.annotation.StaticAnnotation
    
        // 自定义注解
        class myAnnotation(message: String) extends StaticAnnotation
    
        @myAnnotation("This is a custom annotation")
        def myMethod(): Unit = {
          println("This is a method with a custom annotation")
        }
    

    3- 注解的使用场景

    3.1 编译时处理

    某些注解可以在编译时被编译器处理, 提供警告或优化 ;

      @deprecated("This method is deprecated, use another method instead", "1.0")
      def oldMethod(): Unit = {
        println("This is an old method")
      }
    
    3.2 运行时反射

    可以在运行时通过反射读取注解信息

    import scala.annotation.StaticAnnotation
    import scala.reflect.runtime.universe._
    
    // 定义自定义注解
    case class MyAnnotation(message: String) extends StaticAnnotation
    
    // 应用自定义注解到类上
    @MyAnnotation("This is an example class")
    class Example
    
    object AnnotationReader {
      // 获取类上的注解信息
      def getClassAnnotations[T: TypeTag]: List[Annotation] = {
        val tpe = typeOf[T]
        tpe.typeSymbol.annotations
      }
    
      // 打印注解信息
      def printAnnotations[T: TypeTag](): Unit = {
        val annotations = getClassAnnotations[T]
        annotations.foreach { annotation =>
          println(s"Annotation: ${annotation.toString}")
          annotation.tree.children.tail.foreach { arg =>
            println(s" - Argument: ${arg.toString}")
          }
        }
      }
    }
    
    object Main extends App {
      // 读取并打印 Example 类上的注解信息
      AnnotationReader.printAnnotations[Example]()
    }
    

    4- 注解参数

    在Scala中, 注解(Annotation) 就像标签一样, 可以附加到类、方法、字段等代码元素上, 为他们添加额外的信息 ;

    而注解参数, 顾名思义, 就是可以在使用注解时, 像函数调用一样传入一些信息, 用于制定注解的行为 ;

    Scala注解参数支持多种数据类型, 包括:

    • 基本数据类型: 例如 IntDoubleBooleanString 等 ;
    • 数组: 例如 Array[Int]Array[String] 等 ;
    • 类实例: 可以传入自定义的类, 或者 Scala/Java 标准库中的类 ;
    • 枚举值: 可以传入定义好的枚举类型的值 ;

    end

  • 相关阅读:
    直播预告 | 敏捷教练送外卖无限游戏
    【Rust日报】2022-06-25 世界上最大的软件项目的内存安全
    web蓝桥杯真题:冰墩墩心情刻度尺
    Android 实现三维空间坐标系(WebView与JS交互,支持多条曲线,可设置坐标轴翻转等)
    【微服务33】分布式事务Seata源码解析一:在IDEA中启动Seata Server
    ppo-clip的本质以及它为什么是另一种ppo-KL-penalty
    基于 SpringBoot 2.7.x 使用最新的 Elasticsearch Java API Client 之 ElasticsearchClient
    Python学习之CSDN21天学习挑战赛计划 day1
    springBoot中使用easyExcel导出
    LeetCode220720_40、 两数之和 II - 输入有序数组
  • 原文地址:https://blog.csdn.net/Taerge0110/article/details/140381944