4

I am trying to annotate a parameter of a case class.

Judging from this question, and and from this scaladoc, it looks like what I am doing should work, but for some reason it does not:

class Foo extends java.lang.annotation.Annotation { def annotationType = getClass }
case class Bar(@Foo @getter bar: String) 
classOf[Bar].getDeclaredMethods.map(_.getDeclaredAnnotations.length)

res66: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

Any ideas?

Dima
  • 39,570
  • 6
  • 44
  • 70

1 Answers1

1

Write your annotation in Java. Also @getter should be used as a meta-annotation.

Foo.java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Foo {
}

Bar.scala

case class Bar(@(Foo @getter) bar: String)

Then

classOf[Bar].getDeclaredMethods.map(_.getDeclaredAnnotations.length)
// Array(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

Why annotations written in Scala are not accessible at runtime?

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66