我试图在 Scala 反射中看到一个注释,到目前为止还没有骰子。我错过了什么?
我的注释:(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)
输出是对我的案例类字段的成功遍历,但注释列表始终为空,即使我使用 @MongoKey 注释装饰类的字段也是如此。我找错地方了吗?