frazman
frazman

Reputation: 33243

accessing java class from python using jython

I wrote a class in java which i want to execute in python using jython. First the error I am getting?

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)

My Java class format:

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;
    }

My python 2 lines script

import Customer

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

The directory structure is like

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

I went to folder and did

    %javac -classpath Customer.jar *.java

And then my jython is in Users/wolverine/jython/jython

To execute I do this

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

And again the error is :

   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)

Disclaimer. I just started using java :(

Upvotes: 3

Views: 1665

Answers (1)

Gagravarr
Gagravarr

Reputation: 48326

The Customer class isn't in your package, and your constructor isn't public. That's why you're getting the error you see - the constructor isn't visible to your python code (which is in another package effectively)

Change your constructor line from

Customer(int _customerId, String _name){

to

public Customer(int _customerId, String _name){

And it should work fine. In addition, you may find this question helpful on understanding how public / protected / private / default work.

Upvotes: 2

Related Questions