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.
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))