data_person
data_person

Reputation: 4470

Call java method in python with Jpype

Sample Java File:

package com.example.helloworld;

public class SampleClass {

public static int square(int x){
 return x*x;
}

public static void main(String[] args){
    System.out.println(square(4));

  }

}

Local path to Sampleclass.java

C:\\Desktop\\TestProject\\src\\main\\java\\com\\example\\helloworld\\SampleClass.java

I am trying to call square method from SampleClass in Python.

Code from reference Calling java methods using Jpype:

from jpype import *
startJVM(getDefaultJVMPath(),"-ea")
sampleClass = JClass("C:\\Desktop\\TestProject\\src\\main\\java\\com\\example\\helloworld\\SampleClass.java")

print(sampleClass.square(4))

Error:

java.lang.NoClassDefFoundError

Any suggestions on how to correct this will be great.

Upvotes: 1

Views: 4059

Answers (2)

Alejo Herny
Alejo Herny

Reputation: 31

Additionally, for Mac M1 the following resources may be helpful:

from jpype import *
import jpype.imports
from jpype.types import *

# JAVA_HOME =/Users/usr/.jenv/versions/11.0 python3 setup.py install
jvm_dir = "/Users/usr/Applications/zulu/zulu11.58.15-ca-jdk11.0.16-macosx_aarch64/zulu-11.jdk/Contents/MacOS/libjli.dylib"
jpype.startJVM(jvmpath =jvm_dir)
classpath = "/Users/usr/visa_repos/visa_java_jwe/target/jwe-jws-encryption-utils-1.0.1-jar-with-dependencies.jar"
jpype.addClassPath(classpath)
from com.visa.ddp.cise.utils import SampleClass
print(SampleClass.square(4))

Make sure you package referenced jar inclusive of dependencies, Also if issues arise referencing libjli.dylib, you can download JDK and place in /Applications/ see below:

using Azul Java OpenJDK

Azul Java OpenJDK

Using Jpype

Making One Jar inclusive of dependencies

Upvotes: 0

Karl Nelson
Karl Nelson

Reputation: 356

The use of JClass in your test program is incorrect. Java used classpaths to locate the root of the tree to search for methods. This can either be directories or jar files. Java files also need to be compiled so a raw java source file can't be loaded.

First, you will want to compile the test code into a class file using javac. Lets say you did so and it created C:\\Desktop\\TestProject\\src\\main\\classes\\ which contains com\\example\\helloworld\\SampleClass.class.

Then when we start the JVM we give it the path to root of the java classes. You can place as many root directories or jar files as you would like in the classpath list. Java classes are referenced with dot notation just like the package name thus this will be the format used by JClass.

Once you do so then this code should work

from jpype import *
startJVM("-ea", classpath=["C:\\Desktop\\TestProject\\src\\main\\classes\\"])
SampleClass = JClass("com.example.helloworld.SampleClass")

print(SampleClass.square(4))

Upvotes: 2

Related Questions