2013-12-12 85 views
0

我目前正在設法弄清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],這顯然必須失敗。 我的問題是:我怎樣才能向方法調用創建合適的數組? 但是,相同的代碼不適用於列表。我想這是由於類型擦除,這不會發生在數組上。

由於提前,

韋利內

回答

1

不能向下轉換的Array[Object]Array[Foo]。創建您需要的陣列的最簡單方法是:

val arrayFoo = Array.ofDim[Foo](arrayA.length) 
System.arraycopy(arrayA, 0, arrayFoo, 0, arrayA.length) 

請參閱System.arraycopy