1

I am running a Python project, yet there is one library (sikuli) that is loads easier to work with in Java. I was wondering if there was some way I could grant my python program access to the Java class and somehow have the JVM interpret the calls to the Java class from Python.

The other alternative is to make a .jar with all my methods and then just run the jar with arguments with a .subprocess command in Python, which is a little bit messy but would also get the job done.

That1Guy
7,2485 gold badges50 silver badges60 bronze badges
asked Oct 5, 2015 at 18:13
2

2 Answers 2

4

Take a look at Pyjnius. It lets you import a Java class as a Python object and it exposes its methods in a transparent, pythonic way.

Basic example: Using a class in a JAR file

java_resource_jar_path = "/path/to/jar/directory"
jnius_config.set_classpath(java_resource_jar_path)
from jnius import autoclass
# from jnius import JavaException 
# You might have to import JavaException if your class happens to throw exceptions
TheJavaClass = autoclass(path.in.the.jar.file.to.class) # No ".class", no parentheses
python_instance_of_the_Java_class = TheJavaClass()

At this point, python_instance_of_the_Java_class has all the methods of your Java class.

answered Oct 5, 2015 at 18:24
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I'll take a look. In the standalone java class, how would I worry about importing the sikuli-java.jar? In java I add it to the project libraries, but how would I do this in a standalone .java file being referenced by python through pyjnius?
@k9b I added an example that shows you how to use a JAR file.
Thank you very much. Makes tons of sense!
1

Jpype1 allows you to start the JVM with custom jars in your classpath which allows you to virtually use any third-party Java library via Python.

import jpype
jpype.startJVM(jpype.getDefaultJVMPath(), '-ae', "-Djava.class.path=./MyLibrary.jar")
pkg = jpype.JPackage('com').site.myclasses
javaobj = pkg.MyClass()
javaobj.javaMethod()
answered Oct 5, 2015 at 18:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.