scala中的Java类反射

时间:2012-11-26 13:13:45

标签: java scala reflection

我正在尝试在scala上使用java的反射API。我有一个使用ClassLoader从字节码加载的KDTree类。这是方法:

public class KDTree
{
public KDTree(int k)
public void insert(double[] key, Object value) throws Exception
public Object[] range(double[] lowk, double[] uppk) throws Exception
}

这是我的包装scala类:

class KDTree( dimentions: Int )
    //wrapper!
    {
    private val kd= Loader.loadClass("KDTree")
    private val constructor= kd.getConstructor(java.lang.Class.forName("java.lang.Integer"))
    val wrapped= constructor.newInstance("1")
    def insert( key:Array[Double], element:Object)=
        kd.getDeclaredMethod("insert", classOf[Array[Double]])
            .invoke(key, element)
    def range( lowkey:Array[Double], highkey:Array[Double])=
        kd.getDeclaredMethod("range", classOf[Array[Double]])
            .invoke(lowkey, highkey)
    }

当我尝试初始化时,我收到错误:

java.lang.NoSuchMethodException: KDTree.<init>(java.lang.Integer)

但是,构造函数的唯一参数确实是一个整数!

另外,我不能简单地执行java.lang.Integer.class,因为scala抱怨语法:error: identifier expected but 'class' found.

有没有人有任何提示?

修改 这是我完成的代码,以防有人使用它:

class KDTreeWrapper[T]( dimentions: Int )
{
private val kd= Loader.loadClass("KDTree")
private val constructor= kd.getConstructor(classOf[Int])
private val wrapped= constructor.newInstance(dimentions:java.lang.Integer)
    .asInstanceOf[Object]
private val insert_method= kd.
    getMethod("insert", classOf[Array[Double]], classOf[Object])
private val range_method= 
    kd.getMethod("range", classOf[Array[Double]], classOf[Array[Double]])
def insert( key:Iterable[Double], element:T)=
    insert_method.invoke(wrapped, key.toArray, element.
        asInstanceOf[Object])
def range( lowkey:Iterable[Double], highkey:Iterable[Double]):Array[T]=
    range_method.invoke(wrapped, lowkey.toArray, highkey.toArray).
        asInstanceOf[Array[T]]
}

2 个答案:

答案 0 :(得分:3)

您的问题是您尝试加载类型参数为java.lang.Integer的构造函数。试试int.class

kd.getConstructor(int.class)也是时候了。

答案 1 :(得分:0)

我认为我的例子更简单,但那可能是因为我写了它:

class Config {
  val c = "some config"
}

class Moo(c: Config) {
  val x = "yow!"
}

class Loo(c: Config)  extends Moo(c) {
  override val x = c.c + " yodel!"
}

object CallMe {
  def main(args: Array[String]) {
    val cn = new Config

    // val m: Moo = new Loo(cn)

    val c = Class.forName("Loo")
    val ars = c.getConstructor(classOf[Config])
    val m: Moo = ars.newInstance(cn).asInstanceOf[Moo]

    println(m.x)
  }
}

打印出来

some config yodel!