Jython, unresolved import - java class

时间:2016-04-15 14:48:52

标签: python jython

I'm trying out jython, and got stuck pretty early with the example from chapter 10 http://www.jython.org/jythonbook/en/1.0/JythonAndJavaIntegration.html the math import does work from the java library. But I cannot get the custom class Beach to work.

I saw an identical post Jython won't import user-defined class; ImportError: No module named ****** However I did not understand the accepted answers approach.

So I'm hoping for a bit clarification.

Below is my project structure.

enter image description here

import Beach

b = Beach("Cocoa Beach","Cocoa Beach")
print (b.getName(Beach.getName()))

import Beach: Unresolved import: Beach

EDIT: Got it working with the following:

import sys
sys.path.append('C:\Users\Rasmus\Desktop')

import Beach

beach = Beach("Cocoa Beach","Cocoa Beach")
beach.getName()
print(beach.getName())

However pydev eclipse still marks import Beach as an unresolved import.

The Beach class

public class Beach {

    private String name;
    private String city;


    public Beach(String name, String city){
        this.name = name;
        this.city = city;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

}

1 个答案:

答案 0 :(得分:2)

You need to have the compiled class in Jython class path. You can only import compiled class files.

As metioned in the link that you had in your question:

As we had learned in Chapter 8, one thing you’ll need to do is ensure that the Java class you wish to use resides within your CLASSPATH. In the example above, I created a JAR file that contained the Beach class and then put that JAR on the CLASSPATH.

The compilation is done by using javac command which is part of JDK. Creating a jar file is done with the command jar command part of JDK.

It is not a good practice to have files of different files in the same directory. You should create a Java project for your .java file and the Jython files in a separate directory.

Look at using-a-jar-or-java-project-in-your-jython-app.