Go
, often calledGoLang
, is fromGoogleA carefully crafted static typed and compiled programming language. It is known for its concise syntax, excellent concurrency processing capabilities and efficient performance, so it has been widely used in back-end systems, cloud-native applications, and microservice architectures. Go language has its rich standard library, andgoroutines
andchannels
Unique features such as this show significant advantages in developing scalable and efficient programs. Many developers tend toGo
Use it in conjunction with other programming languages, such as Java, to build more powerful multilingual systems. In this article, we will dive into how to call from a Java environmentGoLang
function to achieve seamless integration of two languages.
Dependencies
Before calling Go functions from Java, let's first look at what preparations need to be done:
- Java Development Toolkit (JDK): It is recommended to use JDK 11 or later to ensure compatibility and performance optimization.
-
Go compiler: Make sure Go is installed on your system and that the environment variables are correctly configured for use directly on the command line
go
Order. -
Java Local Interface (JNI):
JNI
It is a mechanism provided by the Java platform to integrate local code (such as C/C++ or Go compiled binary files) with Java code. -
cgo:
cgo
It is a tool in the Go language that allows Go code to interoperate with C code. With cgo, you can generate C-compatible binary files, thus supporting JNI calls. - javac and java: Make sure that the Java compiler and runtime environment are installed so that Java programs are compiled and run.
Functional demonstration
In the next steps, I will explain in detail how to write a Go function, compile it into a shared library, and call the function from Java using JNI (Java Native Interface). The following are the specific steps:
Writing Go functions
First, we need to write a simple Go function and export it asCCompatible symbols so that Java can call it via JNI. Here is an example Go function that takes two integers and returns their sum:
package main import "C" //export AddNumbers func AddNumbers(a, b int) int { // This function receives two integers as input, // Calculate their sum and return the result. return a + b } // main function is necessary to build a shared library.// Even in this case it does nothing.func main() {}
Code explanation:
-
package main
: This is the entry point statement of the Go program. Any Go program that needs to be compiled into an executable file or a shared library must be usedpackage main
。 -
import "C"
: This statement enables interoperability between Go and C. By importingC
Package, Go code can generate C-compatible binary files, thus supporting JNI calls. -
AddNumbers
function: This function receives two integer parametersa
andb
, calculate their sum and return the result. Here is a simple example showing how to process input and return output via a Go function. -
func main() {}
:even thoughmain
The function does not perform any operations here, it is also necessary to build a shared library. Go compiler requiresmain
Functions serve as the entry point of the program.
Compile Go code into a shared library
Next, we need to compile the Go code into a shared library (.so
file) so thatJava
The program can load and call it. Compilation is done using the following command:
go build -o -buildmode=c-shared
Command explanation
-
-o
: Specify the output file name as, this is a shared library file.
-
-buildmode=c-shared
: Tell the Go compiler to generate a C-compatible shared library for calls to other languages (such as Java).
After compilation is completed, two files will be generated:(Shared Library) and
(C header file). The Java program will pass
JNI
load。
Writing Java code
Now, we need to write a Java program to load the shared library and call the Go function. Here is the sample code:
/** * Go caller, used to call the shared library generated by Go. */ public class GoInvoker { static { // Load the shared library generated by Go. // Make sure the library file is in the system library path, or specify its full path. ("add"); // Load the shared library } // Declare a local method corresponding to the Go function. // The method signature must match the parameters and return type of the Go function. public native int AddNumbers(int a, int b); public static void main(String[] args) { GoInvoker invoker = new GoInvoker(); // Call the local method and pass two integers. int result = (10, 20); // Print the result received from the Go function. ("Result from Go Function: " + result); } }
Code explanation:
-
Static blocks (
static { ... }
): When class loads, static blocks will be executed("add")
, loading nameadd
Shared library (i.e.). Make sure the library file is in the system library path, or provides its full path.
-
native
Keywords:native
Used to declare a local method that indicates that the implementation of the method is provided by an external library such as a shared library compiled by Go. -
AddNumbers
method: This method and Go functionAddNumbers
Correspondingly, receive two integer parameters and return an integer. The method signature must exactly match the Go function. -
main
method: existmain
In the method, createGoInvoker
Instance and callAddNumbers
Method, pass parameters10
and20
. The call result is stored inresult
variable and print to console.
Compile and run Java code
After completing the Java code writing, compile and run the program according to the following steps:
- Compile Java code: Use the following command to compile the Java program:
javac
- Run Java programs: Run the program with the following command:
java GoInvoker
-
Make sure the shared library is available: make sure
The file is in the system library path, or specify the path by: On Linux, set
LD_LIBRARY_PATH
Environment variables:
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
On Windows, add the directory where the shared library is located toPATH
in environment variable.
- Output result: If everything is configured correctly, the program will output the following results:
Result from Go Function: 30
Through the above steps, we successfully implemented the function of calling Go functions from Java. This approach combines Java's cross-platform capabilities and Go's high-performance features, and is suitable for complex system development that requires multilingual integration.
Handle complex data types
In actual development, we often need to deal with more complex data types, such as structures. To pass complex data between Go and Java, you can useJSON
Serialize and deserialize as intermediate formats. Here is an example showing how to define a struct in Go and serialize it asJSON
, and parsed in Java via JNI.
Export the structure to JSON
First, we define aPerson
Structure, and write a function to serialize it into a JSON string:
package main import ( "C" "encoding/json" "fmt" ) // Define Person structuretype Person struct { Name string `json:"name"` Ageint`json:"age"` } // Export a function to serialize the structure into a JSON string//export GetPersonJSON func GetPersonJSON() * { person := Person{Name: "John Doe", Age: 30} // Create Person instance jsonData, err := (person)// Serialize to JSON if err != nil { ("Error marshaling data:", err) return nil } return (string(jsonData)) // Returns a C-compatible string} // main function is necessary to build a shared libraryfunc main() {}
Code explanation
-
Person
Structure: Define a containingName
(String type) andAge
Structure of (integral type). -
GetPersonJSON
function:
- This function creates a
Person
instance and serialize it into a JSON string. - use
Functions convert structures to JSON format.
- If serialization fails, the function will return
nil
。 - use
Convert Go strings to C-compatible strings for passing over JNI.
-
main
function: Althoughmain
The function is empty, but it is necessary to build a shared library.
Process JSON and call Go functions
Next, we write code in Java, load the shared library and call the Go function to get the JSON string, and then parse the string:
import .; import .; /** * Go caller, used to call the shared library generated by Go. */ public class GoInvoker { static { // Load the Go shared library ("add"); // Make sure the library name is consistent with the shared library generated by Go } // Declare a local method to call Go functions and receive JSON strings public native String GetPersonJSON(); public static void main(String[] args) { GoInvoker invoker = new GoInvoker(); // Call the Go function to get the JSON string String jsonResult = (); // parse JSON strings try { JSONObject personObject = (jsonResult); String name = ("name"); int age = ("age"); // Print the parsed results ("Name: " + name); ("Age: " + age); } catch (Exception e) { (); } } }
Code explanation:
-
Loading the shared library: use
("add")
Load the shared library generated by Go ()。
-
Local method statement:
public native String GetPersonJSON();
A local method is declared to call the Go function and return a JSON string. - Parse JSON:
- use
Parses the JSON string returned from the Go function.
- extract
name
andage
field and print to console.
- Exception handling: If JSON parsing fails, capture and print the exception information.
Compile and run code
Follow these steps to compile and run the code:
- Compile Go code: Use the following command to compile Go code into a shared library:
go build -o -buildmode=c-shared
- Compile Java code: Use the following command to compile the Java program:
javac -cp .:
(make sureIn the classpath, or use Maven/Gradle to manage dependencies. )
- Run Java programs: Run the program with the following command:
java -cp .: GoInvoker
- Output result: If everything is configured correctly, the program will output the following results:
Name: John Doe Age: 30
Summarize
This article deeply explores how to achieve efficient integration between Java and Go through JNI (Java Native Interface) and shared library technology, from the delivery of basic data types to the processing of complex structures, and comprehensively demonstrates the technical details of cross-language calls. By combining Go's high performance with the ecological advantages of Java, developers can build multilingual systems that are both efficient and scalable. The article not only provides a complete practical guide from Go function compilation to Java calls, but also solves the cross-language interaction problem of complex data types through JSON serialization and deserialization, providing strong technical support for modern distributed systems and microservice architectures. Whether it is back-end development, cloud-native applications, or multilingual microservice integration, this article provides highly valuable solutions.
This is the article about how to call GoLang functions from Java environment. For more related content of calling Go functions in Java environment, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!