jhegedus
jhegedus

Reputation: 20653

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).

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 ??? part such that lists contains Symbols pointing to list1 and list2 ?

If I simply put listType into ??? what should go here ??? then lists becomes empty.

(The code below is taken from an IntelliJ Scala Worksheet in which I was experimenting with possible solutions.)

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 ??? )

Upvotes: 0

Views: 115

Answers (1)

ghik
ghik

Reputation: 10764

If you're interested in vals only:

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

Be aware that this includes only accessible members.

Upvotes: 2

Related Questions