我试图在Scala反射中看到注释,但到目前为止还没有成功。我错过了什么?
My Annotation:(Java)
@Target({ElementType.PARAMETER}) // Also tried ElementType.CONSTRUCTOR
@Retention(RetentionPolicy.RUNTIME)
public @interface MongoKey {
String info = "";
}
和试图使用Scala反射访问它的部分:
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)
输出是对case类字段的一次成功遍历,但是注释List总是空的,即使我用@MongoKey注释修饰了类的一个字段。我找错地方了吗?
这很棘手!注释不是在类的成员上,而是在同伴对象的apply方法中的参数上!
从您的类型中,您应该能够获得伴随对象:
val companion = myType.typeSymbol.companionSymbol
从那里,您可以使用反射来查看apply
方法的参数。