2xsaiko
2xsaiko

Reputation: 1071

Accessing Java Field annotation from scala

I have the following code (most of it is just from another SE question, Scala returns no annotations for a field):

val cls = peripheral.getClass
import scala.reflect.runtime.universe._
val mirror = runtimeMirror(cls.getClassLoader)
val clsSymbol = mirror.staticClass(cls.getCanonicalName)
val decls = clsSymbol.toType.decls.filter(s => s"$s".startsWith("variable "))
for (d <- decls) {
  val classname = classOf[InjectExt].getCanonicalName
  val list = d.annotations.filter(v => v.toString equals classname)
  if (list.nonEmpty) {
    val annotation = list.head
    // what now?
  }
}

where InjectExt is the following Java annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface InjectExt {
    String id() default "auto";
}

This works, but now I get this "annotation" that only has one method: tree(). What can I do to get my InjectExt.id()?
And also, the filtering by toString() really seems like a workaround, but it doesn't look like there's any isVariable or similar that I can use.

Upvotes: 1

Views: 1059

Answers (1)

Dici
Dici

Reputation: 25950

Using pure Java reflection, you can get what you want with much less hassle. I find Scala reflection over-complicated.

object Test {
  class SomeClass {
    @InjectExt(id = "someCoolId") val myMember = 2
    @InjectExt(id = "someOtherCoolId") val myOtherMember = 2
  }

  def getFieldId(fieldName: String, someInstance: SomeClass): String = {
    val myMember = someInstance.getClass.getDeclaredField(fieldName)
    myMember.getDeclaredAnnotation(classOf[InjectExt]).id()
  }

  def main(args: Array[String]): Unit = {
    println(getFieldId("myMember", new SomeClass))
    println(getFieldId("myOtherMember", new SomeClass))
  }
}

Output:

someCoolId
someOtherCoolId

If I were you, I would avoid using Scala reflection unless I cannot do what I want using Java reflection.

Upvotes: 2

Related Questions