【发布时间】:2013-12-31 02:18:11
【问题描述】:
我目前正试图弄清楚 Scala 的类型系统和 Scala 反射的深度。 我有以下示例代码(我的真实代码更复杂,更有意义,但归结为这一点):
abstract class Node
class Foo extends Node
case class ArrayFoo(var subs : Array[Foo]) extends Foo
case class IntFoo(i : Integer) extends Foo
object Main {
def DoSomething(node : AnyRef) : AnyRef = { // Fix this function?
// do some stuff
node
}
def SetArrayWithReflection(n : Node, a : AnyRef) = {
if (a.isInstanceOf[Array[AnyRef]]) {
val arrayA = a.asInstanceOf[Array[AnyRef]].map(f => DoSomething(f)) // FIX this call?
val getter = n.getClass.getMethods.find(p => p.getName == "subs")
val setter = n.getClass.getMethods.find(p => p.getName == "subs_$eq")
if (setter == None) println("Method not found!") else {
println(f"would need to downcast from ${arrayA.getClass.getComponentType} to ${getter.get.getReturnType.getComponentType}")
setter.get.invoke(n, arrayA) // Error happens here
}
}
}
def main(args : Array[String]) : Unit = {
val my = ArrayFoo(Array(IntFoo(1), IntFoo(2), IntFoo(3)))
val newArray = Array(IntFoo(10), IntFoo(20), IntFoo(30))
SetArrayWithReflection(my, newArray)
my.subs.foreach(f => println(f))
}
}
我得到的输出是:
would need to downcast from class java.lang.Object to class Foo
Exception in thread "main" java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at Main$.SetArrayWithReflection(Main.scala:19)
at Main$.main(Main.scala:27)
at Main.main(Main.scala)
通过反射,我尝试使用 Array[Foo] 调用期望 Array[Object] 的方法,这显然必须失败。 我的问题是:我怎样才能向下转换或创建一个合适的数组来调用方法? 但是,相同的代码确实适用于列表。我想这是由于类型擦除不会发生在数组上。
提前致谢,
维林斯
【问题讨论】:
标签: arrays scala types casting