Cam Jackson
Cam Jackson

Reputation: 12294

Why can't Jython find my .jar file?

I have a jar file (not part of the Java standard library) that I want to use.

I've put myJavaPackage.jar into my project directory, and I'm trying to do import myJavaPackage, but I keep getting ImportError: No module named myJavaPackage. What am I doing wrong?

Upvotes: 1

Views: 3532

Answers (1)

Cam Jackson
Cam Jackson

Reputation: 12294

You need to make sure that Jython knows to search your .jar file for modules, which is done using pythonpath. This will differ depending on your setup, but in PyDev:

  1. In the Package Explorer (the tree on the left), right-click on the project and go to Properties.
  2. Select "PyDev - PYTHONPATH" on the left.
  3. Click the "Add zip/jar/egg" button on the right.
  4. Use the directory tree on the left to browse to the folder containing your jar, then click the checkbox next to the .jar file on the right, and click OK, then OK again.

You should also check that the module name you are trying to import matches the package name as specified within the jar file. Note that the jar file might be named differently to the package, especially if there are multiple packages within it.

If you have the source for the .jar, open up the .java file containing the code you wish to utilise, and look for a line near the top that specifies the package. If you find a line that says something like package foo.bar.myJavaPackage;, then you must do one of

  • import it like import foo.bar.myJavaPackage, and use the contents like obj = foo.bar.myJavaPackage.someClass, or
  • import it like from foo.bar import myJavaPackage, and use the contents like obj = myJavaPackage.someClass, or
  • import it like from foo.bar.myJavaPackage import someClass, and use it like obj = myClass, but careful of name collisions using this method.

Upvotes: 3

Related Questions