• 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

  • 相关阅读:
    GBase8s系统表介绍(七)
    初识Nodejs -- nodejs简介
    列表和标签企业报告版的完整报告解决方案
    MathType7 公式编辑器嵌入Word\WPS,MathType 公式编辑常用小技巧
    [附源码]Python计算机毕业设计SSM篮球馆预约小程序(程序+LW)
    【无标题】
    【正点原子STM32连载】 第四十二章 IIC实验 摘自【正点原子】APM32F407最小系统板使用指南
    CSS -webkit-scrollbar 搭配flex时,滚动条按钮显示异常问题记录
    自己搭建的若依DEMO地址
    面试题____Java小白找工作必须领悟的修仙秘籍(二)
  • 原文地址:https://blog.csdn.net/Taerge0110/article/details/140381944