Reading annotations
In Crystal, you normally invoke a method on an object in order to access some data stored within. Annotations are no different. The Annotation
type exposes three methods that can be used to access the data defined on the annotation in different ways. However, before you can access the data on the annotation, you need to get a reference to an Annotation
instance. This can be accomplished by passing the Annotation
type to the #annotation
method defined on the types that support annotations, including TypeNode
, Def
, and MetaVar
. For example, we can use this method to print the annotation applied to a specific class or method, if present:
annotation MyAnnotation; end @[MyAnnotation] class MyClass def foo {{pp @type.annotation MyAnnotation}} {{pp @def.annotation MyAnnotation}} end end MyClass.new.foo
The #annotation
method will return NilLiteral
if no annotation of the provided type is applied...