是否可以使用反射来查找声明为Scala枚举子类型的字段的实际类型? [英] Is it possible to use reflection to find the actual type of a field declared to be a Scala Enumeration subtype?

查看:64
本文介绍了是否可以使用反射来查找声明为Scala枚举子类型的字段的实际类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想自动将字符串转换/强制转换为Scala枚举值,但不事先知道声明来自哪个Enumeration子类(子对象?)。

I want to automatically convert/coerce strings into Scala Enumeration Values, but without knowing beforehand what Enumeration subclass (subobject?) the declaration is from.

因此,给定:

object MyEnumeration extends Enumeration {
  type MyEnumeration = Value
  val FirstValue, SecondValue = Value
}

class MyThing {
  import MyEnumeration._
  var whichOne: MyEnumeration = FirstValue
}

我将如何实现以下目标?

how would I implement the following?

val myThing = new MyThing()
setByReflection(myThing, "whichOne", "SecondValue")

我在找什么就是当我获得MyThing.whichOne类(通过java.lang.Field)时,返回的是 scala.Enumeration $ Value,这不足以让我枚举所有可能值的名称。 / p>

What I'm finding is that when I get the class of MyThing.whichOne (via java.lang.Field), the return is 'scala.Enumeration$Value', which isn't specific enough for me to enumerate the names of all the possible values.

推荐答案

特定类型在运行时丢失,但是您可以在编译时通过隐式捕获。您可以像下面这样在枚举中提供隐式变量。

The specific type is lost at runtime however you can capture it at compile time through implicits. You can provide an implicit in your enum like the following.

object MyEnumeration extends Enumeration {
  type MyEnumeration = Value
  val FirstValue, SecondValue = Value
  implicit def convertMyEnumeration( value: String ) =
    MyEnumeration.withName( value )
}

class MyThing {
  import MyEnumeration._
  var whichOne: MyEnumeration = FirstValue
}

val myThing = new MyThing()
myThing.whichOne = "SecondValue"

如果类型系统无法解析您的枚举以应用正确的隐式,您也可以执行以下操作您的用法可以默认使用多态性,并且提供如下设置方法。

You could also do the following as well if the type system is unable to resolve your enum to apply the correct implicit in your usages you can default to using polymorphism if and provide a setter like the following.

class MySuperThing {
  def setWhichOne( value: String }
}

class MyThing extends MySuperThing {
  import MyEnumeration._
  var whichOne: MyEnumeration = FirstValue
  def setWhichOne( value: String ) = MyEnumeration.withName( value )
}

val myThing: MySuperThing = new MyThing()
myThing.setWhichOne( "SecondValue" )

这篇关于是否可以使用反射来查找声明为Scala枚举子类型的字段的实际类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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