Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotating case class parameters

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?

like image 394
Dima Avatar asked Jun 16 '26 16:06

Dima


1 Answers

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?

like image 84
Dmytro Mitin Avatar answered Jun 19 '26 03:06

Dmytro Mitin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!