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

Scala:用反射来发现你的内心对象(和欲望)?

发布时间:2020-12-16 18:32:30 所属栏目:安全 来源:网络整理
导读:有没有办法在运行时发现在外部对象内声明的对象? Java类方法getClasses和getDeclaredClasses都返回空数组. object Parent { object Child1 object Child2}println("Children of Parent:")println(" getClasses found %d".format(Parent.getClass.getClasses
有没有办法在运行时发现在外部对象内声明的对象? Java类方法getClasses和getDeclaredClasses都返回空数组.

object Parent {
    object Child1
    object Child2
}

println("Children of Parent:")
println("   getClasses found %d".format(Parent.getClass.getClasses.size))
println("   getDeclaredClasses found %d".format(Parent.getClass.getDeclaredClasses.size))

输出是:

Children of Parent:
  getClasses found 0
  getDeclaredClasses found 0

编辑:我已经探索让孩子们与父母一起注册:

object Parent {
    val children = new collection.mutable.ListBuffer[AnyRef]
    object Child1 { Parent.children += this }
    object Child2 { Parent.children += this }
}

println("(1) Parent.children size: %d".format(Parent.children.size))
Parent.Child1
Parent.Child2
println("(2) Parent.children size: %d".format(Parent.children.size))

(虽然这看起来很难看,但实际上还可以,因为我可以通过创意子类和隐式参数来隐藏这些细节.)

这种方法的问题是在引用每个类型(因此调用Parent.Child1和Parent.Child2)之前不会调用静态初始化器,这会破坏目的.输出是:

(1) Parent.children size: 0
(2) Parent.children size: 2

编辑2:我知道数据在那里!使用scalap Parent列出内部对象:

object Parent extends java.lang.Object with scala.ScalaObject {
  def this() = { /* compiled code */ }
  object Child1 extends java.lang.Object with scala.ScalaObject {
    def this() = { /* compiled code */ }
  }
  object Child2 extends java.lang.Object with scala.ScalaObject {
    def this() = { /* compiled code */ }
  }
}

解决方法

为什么不考虑一种更简单的方法,如果可以注册内部对象:

object Parent {
  object Child1 
  object Child2 
  val children = List( Child1,Child2 )
}

scala> Parent.children
res: List[ScalaObject] = List(Parent$Child1$@7493931b,Parent$Child2$@49f0d68)

第二个尝试:

通过将子对象包装在实例中,可以通过反射检索它们,而无需单独注册它们.但是,有一些开销:

trait HasChildren {
  val children: AnyRef
}

object Parent extends HasChildren {
  val children = new {
    object Child1
    object Child2
  }
}

scala> Parent.children.getClass.getDeclaredFields
res: Array[java.lang.reflect.Field] = 
  Array(private volatile Parent$$anon$1$Child1$Parent$$anon$1.Child1$module,private volatile Parent$$anon$1$Child2$Parent$$anon$1.Child2$module)

(编辑:李大同)

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

    推荐文章
      热点阅读