Scala 反射以在运行时访问所有公共字段 [英] Scala reflection to access all public fields at runtime

查看:38
本文介绍了Scala 反射以在运行时访问所有公共字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下类层次结构:

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

class B extends A {
  val z = 5
}

假设我有一个 B 的实例,但不知道它的类层次结构的编译时知识,并且希望能够报告如下内容:

And say I have an instance of B with no compile-time knowledge of its class hierarchy and would like to be able to report something like the following:

Class: B
val[x]: 3
val[y]: 4
val[z]: 5

使用 Scala 反射的最佳方法是什么?

What would be the best approach using Scala reflection?

谢谢德

推荐答案

简述:

import scala.reflect.runtime.universe._

val a = new A
val rm = scala.reflect.runtime.currentMirror
val accessors = rm.classSymbol(a.getClass).toType.members.collect {
  case m: MethodSymbol if m.isGetter && m.isPublic => m 
}
val instanceMirror = rm.reflect(a)
for(acc <- accessors)
  println(s"$a: ${instanceMirror.reflectMethod(acc).apply()}")

这篇关于Scala 反射以在运行时访问所有公共字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆