Installation: Call Java Programs From Julia
Installation: Call Java Programs From Julia
Installation: Call Java Programs From Julia
Installation
Pkg.add("JavaCall")
This package has a dependency on the WinReg package which, on Windows, is used to derive
the location of the JDK automatically.
Loading
using JavaCall
When the module is first loaded, via using or load, it searches for the JVM dynamic library,
libjvm.so|libjvm.dylib|jvm.dll. The search is dependent on the JAVA_HOME environment variable,
which must be set, except on OSX, where the /usr/libexec/java_home command is used to infer
it. In case the library is not found, the module load fails, and no further functionality is
available.
If the JVM library is now found even when it legitimately exists, a workaround is to set the
JAVA_LIB environment variable to the path to library file. However, a better option will be a
pull request updating the library search code.
Currently, as a debugging aid, the module will print the location of the jvm library when it
loads.
Initialisation
JavaCall.init(["-Djava.class.path=$(@__DIR__)"])
The JavaCall.init(args::Array{String, 1}) method must to used to load and initialise the Java
Virtual Machine before any other functions in this module can be called. The args parameter
is an array containing JVM initialisation arguments. This can be used to set, for example, the
system classpath, and the maximum Java heap. Any valid commandline argument to the java
command can be used. Unrecognised arguments are silently discarded.
Referencing types
jlm = @jimport "java.lang.Math"
jnu = @jimport java.net.URL
The @jimport macro returns the Julia type that corresponds to the relevant Java class. This Julia type
can the be used a proxy for the Java type, and can be used for instantiating objects of that class, or
calling static methods on it.
To import the outer and inner clasess, one would use Outer$Inner instead of Outer.Inner.
julia
jouter=@jimport myPackage.Outer
jinner=@jimport myPackage.Outer$Inner
The primary interface to Java methods is the jcall function. Like the inbuilt Julia ccall function, you need to
supply the return type, a tuple of the argument types, and the method arguments themselves. The first argument
to jcall however is the receiver of the method in Java
Example Code :
Create a java file called outer as below:
Outer.java
package myPackage;
public class Outer {
public class Inner{
public void innerMethod() {
System.out.println("In Inner class Method");
}
}
public Inner createrInnerObject() {
Inner innerObj=new Inner();
return innerObj;
}
}
Note:
1. All the .class file should be placed with in respective java file
path.
2. When ever you make changes to java we need to compile the
java file and replace the .class file of the currently compiled
java file.