
Java plugins are specialized Java classes that you can call from Stata. Java plugins are suitable for creating large or complex projects. A plugin can be wrapped up in an ado program and therefore look like any other Stata program when called. For example, you could write a Stata command in Java to pull data from the Federal Reserve Economic Data (FRED). We did, it's the import fred command.
Additionally, the Stata Function Interface (sfi) Java package is included, providing a bidirectional connection between Stata and Java. The sfi package has classes to access Stata's current dataset, frames, macros, scalars, matrices, value labels, characteristics, global Mata matrices, date and time values, and more.
Stata bundles the Java Development Kit (JDK) with its installation, so there is no additional setup involved. This version of Stata includes Java 11, which is the current long-term support (LTS) version.
Did you know that Java code can be embedded directly in do-files, ado-files, or called interactive too. If that sounds interesting, see Java integration.
We will demonstrate just how easy it is to add new features to Stata using Java.
We are going to create a new Stata command tryjava. Here it is in action:
. tryjava hello from java! . _
First, write a hello routine in Java and save it in a .java file:
file HelloFromJava.java | ||
import com.stata.sfi.*; public class HelloFromJava { public static int sayhello(String[] args) { SFIToolkit.displayln("Hello from java!") ; return(0) ; // Stata return code } } | ||
Compile the .java file using the Java compiler.
For this step, you may want to copy sfi-api.jar from your Stata installation to your current directory.
This produces a new file, HelloFromJava.class:
% javac -classpath sfi-api.jar HelloFromJava.java
Build a Java JAR file from this class file. You can name the JAR file whatever you wish. We will call it tryjava.jar:
% jar cvf tryjava.jar HelloFromJava.class
Copy the JAR file to your PERSONAL directory. (In Stata, type sysdir to find out where your PERSONAL directory is.)
Now write a Stata ado-file:
file tryjava.ado | ||
program tryjava version 17 javacall HelloFromJava sayhello, jar(tryjava.jar) end | ||
file tryjava.ado |
That's it.
Learn more about Stata's programming features.
To read more, see [P] java intro, [P] javacall, and visit stata.com/java.