【问题标题】:Java classes reflection in scalascala中的Java类反射
【发布时间】:2012-11-13 23:23:08
【问题描述】:

我正在尝试在 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 scala reflection


【解决方案1】:

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

kd.getConstructor(int.class)也更短。

【讨论】:

  • 正如我提到的,在 scala anything.class 抱怨
  • 使用classOf[Integer]classOf[int] 和描述的here
【解决方案2】:

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

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!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多