使用Python中的Scala和JPype

时间:2016-02-09 17:05:51

标签: scala scala-java-interop jpype

我有一个系统,我通过JPype从Python调用Java程序。我想将我的Java代码切换到Scala。例如,我有:

package jnets;

class JVector{
    double [] x;
    public JVector(double[] vec){
        this.x = vec;
    }
    public double[] plus(double[] y){
        assert (x.length==y.length);
        double[] z = new double[x.length];
        for (int i=0; i<x.length; i++)
            z[i] = x[i]+y[i];
        return z;
        }
    }

用javac编译这个文件后,我可以调用(在Python中):

import jpype as jp
import os
import numpy as np
jp.startJVM('/Library/Java/JavaVirtualMachines/jdk1.8.0_66.jdk/Contents/MacOS/libjli.dylib')
c = jp.JClass('jnets.JVector')(np.random.randn(5))

现在,我尝试在Scala中做同样的事情:

package jnets;

class SVector(xi: Array[Double]){
  var x = xi
  def plus(y: Array[Double]): Array[Double] = {
    assert(x.length==y.length)
    val z = Array[Double](x.length)
    for (i <- 0 until x.length)
      z(i) = x(i)+y(i)
    return z
  }
}

现在,如果我将c = jp.JClass('jnets.JVector')(np.random.randn(5))替换为c = jp.JClass('jnets.SVector')(np.random.randn(5)),我会收到错误消息:

jpype._jexception.RuntimeExceptionPyRaisable: java.lang.RuntimeException: Class jnets.SVector not found

那么,怎么了?如果我javap JVector.class我得到了:

class jnets.JVector {
  double[] x;
  static final boolean $assertionsDisabled;
  public jnets.JVector(double[]);
  public double[] plus(double[]);
  static {};
}

如果我javap SVector.class,我得到:

public class jnets.SVector {
  public double[] x();
  public void x_$eq(double[]);
  public double[] plus(double[]);
  public jnets.SVector();
  public jnets.SVector(double[]);
}

所以....我猜这与Java类中的这个static {};行有关,但是可以弄清楚如何让scalac使.class文件与java文件相同。

有什么想法吗?

0 个答案:

没有答案