加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

请参阅Scala反射中的注释

发布时间:2020-12-16 19:15:26 所属栏目:安全 来源:网络整理
导读:我试图在 Scala反射中看到一个注释,到目前为止还没有骰子.我错过了什么? 我的注释:( Java) @Target({ElementType.PARAMETER}) // Also tried ElementType.CONSTRUCTOR@Retention(RetentionPolicy.RUNTIME)public @interface MongoKey { String info = "";}
我试图在 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)

输出是我的case类字段的成功遍历,但是注释List总是空的,即使我使用@MongoKey注释装饰类的字段.我在找错了地方吗?

解决方法

这很棘手!注释不在您的类的成员上,而是实际上在您的伴随对象的apply方法中的参数上!

从您的类型,您应该能够获得伴侣对象:

val companion = myType.typeSymbol.companionSymbol

从那里你可以使用反射来查看apply方法的参数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读