How can I import a custom java class in python?

1,041 views
Skip to first unread message

guil...@intellisense.io

unread,
Jun 19, 2018, 12:42:55 PM6/19/18
to Jep Project
Wiki's tutorial has some instructions as to how call java constructors / java methods from python:

# importing the java.lang.Class objects
from java.lang import Integer
from java.util import ArrayList as AL

# instantiation
x = Integer(5)
y = Integer(51)
a = AL()

I created a very simple python script that instantiates a custom class (test.py):

# importing the java.lang.Class objects
from mypackage import car

# instantiation
x = Car(5)

and tried to run on intellij:

import mypackage.Car;
import jep.Jep;

public class FirstVersion {
public static void main(String[] args) {
try (Jep jep = new Jep()){
// this works
Car c = new Car(5);
System.out.println("Java: " + c.n);

// this doesn't
jep.runScript("/home/ubuntu/test.py");
} catch (Exception e) {
System.out.println(e);
}
}
}

and got following error:

Java: 5
jep.JepException: <class 'ModuleNotFoundError'>: No module named 'mypackage'

Process finished with exit code 0

Is this possible? If so, what am I doing wrong?

Thank you,

Nathan Jensen

unread,
Jun 19, 2018, 2:41:17 PM6/19/18
to Jep Project
Your syntax is correct, thanks for the nice formatting.  Is mypackage.Car on the classpath?  Since you got ModuleNotFounderError as opposed to ClassNotFoundException, that tells us it was looking for the package in Python.  Jep has an interface ClassEnquirer that determines whether an import should be from Java or Python.  If not specified, the default ClassEnquirer is the class ClassList which includes all the classes that come with the JRE and anything on the classpath.  If you think the class is on the classpath, try putting a breakpoint in ClassList.loadClassPath().  Now that I think about it, that's looking for jars and you probably don't have a jar in the IDE at this time.  Try putting a breakpoint in ClassList.loadPackages() as that is looking at the ClassLoader's .class files.  You can also put a breakpoint in ClassList.isJavaPackage() to see what's in the maps of packages when the importer tries to pick whether to import from Java or Python.

--
You received this message because you are subscribed to the Google Groups "Jep Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jep-project...@googlegroups.com.
To post to this group, send email to jep-p...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/jep-project/6ea3bc29-f8b2-44e9-91e0-1687a1c68358%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

guil...@intellisense.io

unread,
Jun 20, 2018, 1:09:58 PM6/20/18
to Jep Project
Thanks Nathan, mypackage.Car was not on the classpath. For IntelliJ what I had to do was add the mypackage folder as a Sources Root and now it's working fine :)
Reply all
Reply to author
Forward
0 new messages