23.1. Tworzenie adnotacji

Adnotacje pozwalają na umieszczenie w kodzie programu informacji dotyczących samego kodu. Adnotacje tworzy się definiując klasy dziedziczące z abstrakcyjnej klasy Annotation z pakietu scala.annotation. Jeśli klasa adnotacji dziedziczy z ClassfileAnnotation (cecha rozszerzająca Annotation), to informacje o takich adnotacjach, znajdujących się w kodzie źródłowym jakiejś klasy, są umieszczane w plikach klas generowanych podczas kompilacji tej klasy. Adnotacje tworzone w języku Scala nie są widoczne w czasie wykonywania programu, a więc nie można ich odczytać korzystając z mechanizmu refleksji języka Java. Jeśli potrzebujemy adnotacji, które byłyby dostępne w czasie wykonywania programu, możemy je napisać w języku Java i skompilować kompilatorem tego języka. Plik CodeAnnotations.scala zawiera definicje kilku adnotacji, które mogą posłużyć do komentowania kodu źródłowego programów w języku Scala.

Plik CodeAnnotations.scala:
import scala.annotation._
class author(final val value: String) extends ClassfileAnnotation
class version(val major: Int, val minor: Int) extends ClassfileAnnotation
class fixme(comment: String = "") extends Annotation
class todo extends Annotation
class comment(comment: String) extends Annotation

Kompilacja pliku powoduje wystąpienie ostrzeżeń dotyczących adnotacji author i version. Te adnotacje dziedziczą z ClassfileAnnotation. Ostrzeżenia zwracają uwagę na to, że tak utworzone adnotacje są niewidoczne w czasie wykonywania programu. Mimo ostrzeżeń, kod kompiluje się i adnotacje mogą być używane.

$ scalac CodeAnnotations.scala
CodeAnnotations.scala:2: warning: Implementation restriction: subclassing Classfile does not
make your annotation visible at runtime.  If that is what
you want, you must write the annotation class in Java.
class author(final val value: String) extends ClassfileAnnotation
      ^
CodeAnnotations.scala:3: warning: Implementation restriction: subclassing Classfile does not
make your annotation visible at runtime.  If that is what
you want, you must write the annotation class in Java.
class version(val major: Int, val minor: Int) extends ClassfileAnnotation
      ^
two warnings found
$ scalac WrongAnnotation.scala
WrongAnnotation.scala:3: error: inner classes cannot be classfile annotations
  class author(final val name: String) extends ClassfileAnnotation
        ^
one error found

Język programowania Scala Wydanie 2. Copyright © Grzegorz Balcerek 2016

Licencja Creative Commons

Ten utwór jest dostępny na licencji Creative Commons Uznanie autorstwa-Na tych samych warunkach 4.0 Międzynarodowe.

Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.