繁体   English   中英

Scala中的Java类反射

[英]Java classes reflection in scala

我正在尝试在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]]
}

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

同样,写kd.getConstructor(int.class)也更短。

我认为我的示例要简单得多,但这可能是因为我编写了它:

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!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM