简体   繁体   English

Scala反射:如何找到具有指定类型的val?

[英]Scala Reflection: How to find vals having a specified type?

I am trying to implement a deep equals comparison using reflection. 我正在尝试使用反射实现深度等于比较。 For that I need to find lists in an object given at runtime (in the example below this object is called Foo ). 为此,我需要在运行时给出的对象中找到列表(在下面的示例中,此对象称为Foo )。

My feeling is that the code below is going towards the right direction, however I cannot figure out what to put into the ??? what should go here ??? 我的感觉是下面的代码正朝着正确的方向发展,但是我无法弄清楚该怎么做??? what should go here ??? ??? what should go here ??? part such that lists contains Symbols pointing to list1 and list2 ? 部分lists包含指向list1list2符号?

If I simply put listType into ??? what should go here ??? 如果我只是将listType放入??? what should go here ??? ??? what should go here ??? then lists becomes empty. 然后lists变空。

(The code below is taken from an IntelliJ Scala Worksheet in which I was experimenting with possible solutions.) (下面的代码来自IntelliJ Scala工作表,我在其中试验可能的解决方案。)

import scala.reflect.runtime.universe._
import java.util
class Foo{
  val one=1
  val list1=new util.ArrayList[Int]
  val list2=new util.ArrayList[Int]  
}
val foo=new Foo
val m= runtimeMirror(getClass.getClassLoader)
val theType =m.reflect(foo).symbol.toType
val listType = typeOf[util.List[_]]
val lists=theType.members.filter(  _.typeSignature == ??? what should go here ??? )

If you're interested in val s only: 如果您只对val s感兴趣:

val lists = theType.members.filter {
  m => m.isTerm && m.asTerm.isVal && m.typeSignature <:< listType
}

Be aware that this includes only accessible members. 请注意,这仅包括可访问的成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM