在Scala/Java中获取实例的公共字段(及其各自的值) [英] Getting public fields (and their respective values) of an Instance in Scala/Java

查看:54
本文介绍了在Scala/Java中获取实例的公共字段(及其各自的值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP引入了一种方法,可让您挑选出以下所有公开值:一个实例.在Scala中有什么方法可以做到这一点?那就是获取实例化类(不是对象)的所有公共字段的所有值.

PHP introduces a method that allows you to pick out all public values of an instance. Is there any way to do this in Scala? That is to fetch all values of all public fields of an instantiated class (not object).

让我们假设我有这堂课

class TestElement( datatype: Datatype, var subject: String, var day: Int, var time: Int )
  extends DataElement( datatype: Datatype ) {    
   def to( group: Group ) = group.add( this );
}

var element = new TestElement( datatype, "subject", 1, 1 );

我需要的方法是获取一个Map或两个值的集合.

What I need from the method in question, is to get a Map or two Collections of values.

var element.method                                       // the function I need
ret: ( ("subject", "subject"), ("day", 1), ("time", 1) ) // its output

推荐答案

是时候上床睡觉了,所以我没有时间做个完整的答案,而是看看 element.getClass.getFields 的结果.code>(或私有字段的 getDeclaredFields )-您可以在 Field 对象上调用 getValue(element)以获取其值.

It's time for bed, so I don't have time for a full answer, but look at the results of element.getClass.getFields (or getDeclaredFields for private fields) - you can call getValue(element) on the Field objects to fetch their values.

现在醒来,仍然没有更好的答案,所以:

Awake now, and still no better answer, so:

首先,请注意,用Java术语来说,您的类没有公共字段主题,它是一个私有字段主题以及访问器方法subject()和subject_ $ eq(String).

First, note that in Java terms, your class doesn't have a public field subject, what it has is a private field subject and accessor methods subject() and subject_$eq(String).

您可以如上所述遍历私有字段对象,从对中填充Map:

You can iterate over the private field objects as described above, populating a Map from the pairs:

def getFields(o: Any): Map[String, Any] = {
  val fieldsAsPairs = for (field <- o.getClass.getDeclaredFields) yield {
    field.setAccessible(true)
    (field.getName, field.get(o)) 
  }
  Map(fieldsAsPairs :_*)
}

现在,您可以在TestElement上定义此方法(用 this 替换 o ),或者更一般地更有用地定义一个转换,以便您可以在任何引用上调用getFields

Now you can either define this method on TestElement (replacing o with this), or more generally usefully define a conversion so that you can call getFields on any reference

implicit def any2FieldValues[A](o: A) = new AnyRef {
  def fieldValues = getFields(o)
}

如此

element.fieldValues 

将给出您想要的结果.

这篇关于在Scala/Java中获取实例的公共字段(及其各自的值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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