Call java method in python with Jpype

Question:

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.

Asked By: data_person

||

Answers:

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))
Answered By: Karl Nelson

I want to know how to call the below main method from python?

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

  }
Answered By: Ashok Sarshan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.