Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

See annotations in Scala reflection

I'm trying to see an annotation in Scala reflection and so far no dice. What am I missing?

My Annotation: (Java)

@Target({ElementType.PARAMETER})  // Also tried ElementType.CONSTRUCTOR
@Retention(RetentionPolicy.RUNTIME)
public @interface MongoKey {
    String info = "";
}

And the part that tries to access it using Scala reflection:

case class One( 
@MongoKey name  : String, 
    stuff : List[String]
)

val targetObj = One("FOO", List("a","b"))
val targetType = typeOf[One]

// Given an object (case class) the Type of the case class, and a field name,
// retrieve the typed field object from the case class.
def unpack[T](target: T, t: Type, name: String): (Any, Type) = {
   val im = cm.reflect(target)(ClassTag(target.getClass))
   val fieldX = t.declaration(newTermName(name)).asTerm.accessed.asTerm
   val fm = im.reflectField(fieldX)
   (fm.get, fm.symbol.typeSignature)  // return the field's value + Type
}

val (pval,pvalType) = SeeMe.unpack(targetObj, targetType, "name")
println(" -> "+pvalType.typeSymbol.annotations)

The output is a successful traversal of my case class' field but the annotation List is always empty, even if I decorate a field of the class with my @MongoKey annotation. Am I looking in the wrong place?

like image 867
Greg Avatar asked Jun 11 '13 18:06

Greg


1 Answers

This is tricky! The annotation is not on the member of your class, but actually on the parameter in the apply method of your companion object!

From your type, you should be able to get the companion object with:

val companion = myType.typeSymbol.companionSymbol

From there you can use reflection to look at the parameters to the apply method.

like image 105
Andy Avatar answered Sep 20 '22 14:09

Andy