有什么方法可以使用反射在运行时访问 Scala 选项声明的类型吗?

发布于 2024-08-30 01:38:59 字数 683 浏览 5 评论 0原文

所以,我有一个如下所示的 Scala 类:

class TestClass {
  var value: Option[Int] = None
}

我正在解决一个问题,我有一个 String 值,并且我想在运行时使用反射将其强制到该 Option[Int] 中。因此,在另一段代码(对 TestClass 一无所知)中,我有一些如下代码:

def setField[A <: Object](target: A, fieldName: String, value: String) {
  val field = target.getClass.getDeclaredField(fieldName)
  val coercedValue = ???; // How do I figure out that this needs to be Option[Int] ? 
  field.set(target, coercedValue)   
}

为此,我需要知道该字段是一个 Option 并且该 Option 的类型参数是 Int。

在运行时(即使用反射)确定“值”的类型是 Option[Int] 时,我有哪些选择?

我已经看到通过注释字段解决了类似的问题,例如@OptionType(Int.class)。如果可能的话,我更喜欢不需要在反射目标上进行注释的解决方案。

So, I have a Scala class that looks like this:

class TestClass {
  var value: Option[Int] = None
}

and I'm tackling a problem where I have a String value and I want to coerce it into that Option[Int] at runtime using reflection. So, in another piece of code (that knows nothing about TestClass) I have some code like this:

def setField[A <: Object](target: A, fieldName: String, value: String) {
  val field = target.getClass.getDeclaredField(fieldName)
  val coercedValue = ???; // How do I figure out that this needs to be Option[Int] ? 
  field.set(target, coercedValue)   
}

To do this, I need to know that the field is an Option and that the type parameter of the Option is Int.

What are my options for figuring out that the type of 'value' is Option[Int] at runtime (i.e. using reflection)?

I have seen similar problems solved by annotating the field, e.g. @OptionType(Int.class). I'd prefer a solution that didn't require annotations on the reflection target if possible.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

葬﹪忆之殇 2024-09-06 01:39:00

使用 Java 1.5 反射 API 非常简单:

 def isIntOption(clasz: Class[_], propertyName: String) = {
   var result = 
     for {
       method <- cls.getMethods
       if method.getName==propertyName+"_$eq"
       param <- method.getGenericParameterTypes.toList.asInstanceOf[List[ParameterizedType]]
     } yield
       param.getActualTypeArguments.toList == List(classOf[Integer]) 
       && param.getRawType == classOf[Option[_]]
   if (result.length != 1)
     throw new Exception();
   else
     result(0)
 }

It's quite streightforward using Java 1.5 reflection API:

 def isIntOption(clasz: Class[_], propertyName: String) = {
   var result = 
     for {
       method <- cls.getMethods
       if method.getName==propertyName+"_$eq"
       param <- method.getGenericParameterTypes.toList.asInstanceOf[List[ParameterizedType]]
     } yield
       param.getActualTypeArguments.toList == List(classOf[Integer]) 
       && param.getRawType == classOf[Option[_]]
   if (result.length != 1)
     throw new Exception();
   else
     result(0)
 }
殊姿 2024-09-06 01:39:00

在字节码级别,Java 还没有泛型。泛型是通过多态性实现的,因此一旦编译了源代码(在本例中为 Scala),泛型类型就会消失(这称为 类型擦除 )。这使得无法通过反射收集通用运行时类型信息。

一个可能的(虽然有点脏)解决方法是获取属性的运行时类型,您知道它与通用参数具有相同的类型。对于 Option 实例,我们可以使用 get 成员

object Test {

  def main(args : Array[String]) : Unit = {
    var option: Option[_]= None
    println(getType(option).getName)
    option = Some(1)
    println(getType(option).getName)

  }

  def getType[_](option:Option[_]):Class[_]= {
         if (option.isEmpty) classOf[Nothing] else (option.get.asInstanceOf[AnyRef]).getClass
  }
}

At the byte code level, Java hasn't got Generics. Generics are implemented with polymorphism, so once your source code (in this case Scala) is compiled, generic types disappear (this is called type erasure ). This makes no possible to gather Generic runtime type information via reflection.

A possible --though little dirty-- workaround is to obtain the runtime type of a property you know it has the same type as the Generic parameter. For Option instances we can use get member

object Test {

  def main(args : Array[String]) : Unit = {
    var option: Option[_]= None
    println(getType(option).getName)
    option = Some(1)
    println(getType(option).getName)

  }

  def getType[_](option:Option[_]):Class[_]= {
         if (option.isEmpty) classOf[Nothing] else (option.get.asInstanceOf[AnyRef]).getClass
  }
}
寻梦旅人 2024-09-06 01:39:00
class TestClass {
  var value: Option[Int] = None
// ...

  def doSomething {
    value match {
      case Some(i) => // i is an Int here
      case None =>
      // No other possibilities
    }
  }
}
class TestClass {
  var value: Option[Int] = None
// ...

  def doSomething {
    value match {
      case Some(i) => // i is an Int here
      case None =>
      // No other possibilities
    }
  }
}
叫思念不要吵 2024-09-06 01:39:00

问题在于 JVM 通过类型擦除来实现泛型。因此不可能通过反射发现 value 的类型是 Option[Int] 因为在运行时它实际上不是:它只是 Option< /代码>!

在 2.8 中,您应该能够使用 清单如下所示:

var value: Option[Int] = None
val valueManifest = implicitly[scala.reflect.Manifest[Option[Int]]]
valueManifest.typeArguments // returns Some(List(Int))

The problem is that JVM implements generics through type erasure. So it's impossible to discover through reflection that the type of value is Option[Int] because at the run-time it actually isn't: it's just Option!

In 2.8 you should be able to use Manifests like this:

var value: Option[Int] = None
val valueManifest = implicitly[scala.reflect.Manifest[Option[Int]]]
valueManifest.typeArguments // returns Some(List(Int))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文