Polyglot Programming(Multi-Language)
Programming In Multi-Language with Java (Java Process Class, JNI & IO)
What is Programming in Multi-Language?
Programming in multiple languages, often referred to as "polyglot programming," involves using different programming languages within the same project or across different projects to leverage the strengths and unique features of each language. This approach allows developers to use the best tool for a specific task, improving efficiency, performance, and maintainability. Well, at the first go, it may seem to be weird to use more than one language, compile codes in more than one language but at the end of the day, it is very useful.
History of Programming Languages:
The history of programming languages is rich and diverse, spanning over several decades and marked by significant innovations and milestones. It was in the 1940s when assembly-level programming languages came into existence. 1951 – the Regional Assembly language came into existence. 1958 – ALGOL; 1959 – COBOL (Common Business Oriented Language) and finally BASIC (Beginners All-purpose Symbolic Instruction Code) in 1964. Finally, we got C in 1972. Python came in 1990 but it only got popular in the current days due to the advent of Data Science and Machine Learning techniques. Java came into existence in 1995. Other languages like Go, Rust, Dark, Kotlin, Swift, Scala, Scratch, etc. are very recent developments.
It is agreeable that different programming languages have different capabilities. For example, C and C++ support pointers; Python is good for Data Science and AI-based fields; R is good for Data analytics and mathematical operations.
1. Overview of Multi-Language Programming in Java
Java applications sometimes need to interact with code written in other languages like C, C++, or Python. This interaction can be necessary for performance reasons, to use existing libraries, or to interface with system-level code.
2. Using the Process Class to Execute External Programs
The Process class in Java is part of the java.lang package and provides methods to handle native system processes. This is useful when you need to run external programs from within your Java application.
Example: Running a Python Script
Here's how you can use the Process class to execute a Python script from Java:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExecutePythonScript {
public static void main(String[] args) {
try {
// Define the command and parameters
String command = "python";
String scriptPath = "/path/to/your/script.py";
ProcessBuilder processBuilder = new ProcessBuilder(command, scriptPath)
// Start the process
Process process = processBuilder.start();
// Capture the output
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// Wait for the process to finish
int exitCode = process.waitFor();
System.out.println("Process exited with code: " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
In this example:
3. Introduction to Java Native Interface (JNI)
JNI (Java Native Interface) allows Java code running in the JVM to call and be called by native applications and libraries written in other languages like C or C++.
Creating a JNI Example
Step 1: Write Java Code
Create a Java class with native methods:
public class HelloWorld {
// Load the native library
static {
System.loadLibrary("HelloWorld");
}
// Declare a native method
public native void sayHello();
public static void main(String[] args) {
new HelloWorld().sayHello();
}
} public class HelloWorld {
// Load the native library
static {
System.loadLibrary("HelloWorld");
}
// Declare a native method
public native void sayHello();
public static void main(String[] args) {
new HelloWorld().sayHello();
}
}
Step 2: Generate the Header File
Compile the Java code and generate the JNI header file:
领英推荐
javac HelloWorld.java
javah -jni HelloWorld
Step 3: Implement the Native Method
Write the C/C++ implementation of the native method:
#include <jni.h>
#include <stdio.h>
#include "HelloWorld.h"
JNIEXPORT void JNICALL Java_HelloWorld_sayHello(JNIEnv *env, jobject obj) {
printf("Hello from C!\n");
}
Step 4: Compile the Native Code
Compile the C/C++ code into a shared library:
gcc -shared -o libHelloWorld.so -I${JAVA_HOME}/include -I${JAVA_HOME}/include/linux HelloWorld.c?
Step 5: Run the Java Program
Ensure the shared library is in your library path and run the Java program:
java -Djava.library.path=. HelloWorld
4. Java I/O Operations with External Processes and JNI
Handling I/O with external processes and JNI involves managing data exchange between Java and external systems.
Example: Writing Data to an External Process
Modify the previous Process example to write data to the process:
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
public class WriteToProcess {
public static void main(String[] args) {
try {
ProcessBuilder processBuilder = new ProcessBuilder("python", "/path/to/your/script.py");
Process process = processBuilder.start();
// Write data to the process
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
writer.write("Data to pass to the script");
writer.flush();
writer.close();
// Capture the output
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// Wait for the process to finish
int exitCode = process.waitFor();
System.out.println("Process exited with code: " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
In this example:
Conclusion:
As we have seen, the Process class can be used to call programs written in other languages, as well as shell scripts. It is quite imperative to say that Process class can also be used to interact with connected hardware as the machine does when there is no proper library in java for the same. Here, we are mainly talking about Serial Communication devices.
?
The Process class and using multiple programming languages in a single project can be a lifesaver when the time is very little and appropriate libraries are not available in a single language. For example, we are not very fluent in Python. We are more of a Java programmer. Hence, we mainly write programs in Java, but there are some instances when Python has better libraries. We can easily use the Process class for invoking them.
?
Note: Be aware of libraries like Jython that might be able to run Python scripts from Java directly, but we are not talking solely about python. Process class can run programs from each and every programming language as long as it is supported on your machine, and you don’t need to learn other libraries to achieve the same. It would be very helpful in projects. Like you want to analyze a huge amount of data you get in your program written in Java. One can simply pass on the data to a program in R or in Python to analyze the data instead of doing the same manually on Java.
?
?