Scala reflection to access all public fields at runtime

前端 未结 3 1691
栀梦
栀梦 2021-01-04 11:23

Given the following class hierarchy:

class A {
  val x = 3
  val y = 4
}

class B extends A {
  val z = 5
}

And say I have an instance of B

3条回答
  •  时光说笑
    2021-01-04 11:38

    Here is a slightly other way to do it:

    scala> val i = 10
    i: Int = 10
    
    scala> val ru=scala.reflect.runtime.universe
    ru: scala.reflect.api.JavaUniverse = scala.reflect.runtime.JavaUniverse@2096fb9f
    
    scala> val m = ru.runtimeMirror(getClass.getClassLoader)
    m: ru.Mirror = JavaMirror with scala.tools.nsc.interpreter.IMain$TranslatingClassLoader@3ae5ce58 of type class scala.tools.nsc.interpreter.IMain$TranslatingClassLoader with classpath [(memory)] and parent being scala.tools.nsc.util.ScalaClassLoader$URLClassLoader@454e119d of type class scala.tools.nsc.util.ScalaClassLoader$URLClassLoader with classpath [file:/Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home/jre/lib/resources.jar,file:/Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home/jre/lib/rt.jar,file:/Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home/jre/lib/jsse.jar,file:/Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home/jre/lib/jce.jar,file:/Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home/jre/lib/charsets.jar,file:...
    scala> val im=m.reflect(i)
    im: ru.InstanceMirror = instance mirror for 10
    
    scala> val is =im.symbol
    is: ru.ClassSymbol = class Int
    
    scala> val ims=is.toType.members
    ims: ru.MemberScope = Scopes(method getClass, constructor Int, method ##, method asInstanceOf, method isInstanceOf, method toString, method hashCode, method equals, method !=, method ==, method %, method %, method %, method %, method %, method %, method %, method /, method /, method /, method /, method /, method /, method /, method *, method *, method *, method *, method *, method *, method *, method -, method -, method -, method -, method -, method -, method -, method +, method +, method +, method +, method +, method +, method +, method ^, method ^, method ^, method ^, method ^, method &, method &, method &, method &, method &, method |, method |, method |, method |, method |, method >=, method >=, method >=, method >=, method >=, method >=, method >=, method >, method >, method >, met...
    scala> 
    

    ims can then be further filtered any way you like.

提交回复
热议问题