使用jython从python访问java类

时间:2012-12-26 03:34:15

标签: java python jython

我在java中编写了一个类,我希望使用jython在python中执行。 首先是我得到的错误?

Traceback (most recent call last):
  File "/Users/wolverine/Desktop/project/jython_scripts/customer.py", line 3, in <module>
    customer = Customer(1234,"wolf")
TypeError: No visible constructors for class (Customer)

我的Java类格式:

public class Customer {
    public final int customerId;
    public final String name;
    public double balance;

    /*
     *  Constructor
     */
    Customer(int _customerId, String _name){
        customerId = _customerId;
        name = _name;
        balance = 0;
    }

我的python 2行脚本

import Customer

customer = Customer(1234,"wolf")
print customer.getName()

目录结构类似于

 folder/customer.py    folder/Customer.java folder/Customer.jar

我去了文件夹并做了

    %javac -classpath Customer.jar *.java

然后我的jython在Users / wolverine / jython / jython

执行我这样做

       %/Users/wolverin/jython/jython ~/Desktop/folder/customer.py

错误再次出现:

   Traceback (most recent call last):
  File "/Users/wolverine/Desktop/project/jython_scripts/customer.py", line 3, in <module>
    customer = Customer(1234,"wolf")
TypeError: No visible constructors for class (Customer)

声明。我刚开始使用java:(

1 个答案:

答案 0 :(得分:2)

Customer类不在您的包中,并且您的构造函数不是公共的。这就是为什么你得到你看到的错误 - 你的python代码(有效地在另一个包中)看不到构造函数

更改构造函数行
Customer(int _customerId, String _name){

public Customer(int _customerId, String _name){

它应该可以正常工作。此外,您可能会发现this question有助于了解public / protected / private / default的工作方式。