SoFunction
Updated on 2025-04-14

How to call GoLang function from Java environment

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, andgoroutinesandchannelsUnique features such as this show significant advantages in developing scalable and efficient programs. Many developers tend toGoUse 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 environmentGoLangfunction 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 linegoOrder.
  • Java Local Interface (JNI)JNIIt is a mechanism provided by the Java platform to integrate local code (such as C/C++ or Go compiled binary files) with Java code.
  • cgocgoIt 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:

  1. 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
  2. import "C": This statement enables interoperability between Go and C. By importingCPackage, Go code can generate C-compatible binary files, thus supporting JNI calls.
  3. AddNumbersfunction: This function receives two integer parametersaandb, calculate their sum and return the result. Here is a simple example showing how to process input and return output via a Go function.
  4. func main() {}:even thoughmainThe function does not perform any operations here, it is also necessary to build a shared library. Go compiler requiresmainFunctions 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 (.sofile) so thatJavaThe 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 passJNIload

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:

  1. Static blocks (static { ... }: When class loads, static blocks will be executed("add"), loading nameaddShared library (i.e.). Make sure the library file is in the system library path, or provides its full path.
  2. nativeKeywordsnativeUsed 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.
  3. AddNumbersmethod: This method and Go functionAddNumbersCorrespondingly, receive two integer parameters and return an integer. The method signature must exactly match the Go function.
  4. mainmethod: existmainIn the method, createGoInvokerInstance and callAddNumbersMethod, pass parameters10and20. The call result is stored inresultvariable 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:

  1. Compile Java code: Use the following command to compile the Java program:
javac 
  1. Run Java programs: Run the program with the following command:
java GoInvoker
  1. Make sure the shared library is available: make sureThe file is in the system library path, or specify the path by: On Linux, setLD_LIBRARY_PATHEnvironment variables:
export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH

On Windows, add the directory where the shared library is located toPATHin environment variable.

  1. 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 useJSONSerialize 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 aPersonStructure, 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

  1. PersonStructure: Define a containingName(String type) andAgeStructure of (integral type).
  2. GetPersonJSONfunction
  • This function creates aPersoninstance and serialize it into a JSON string.
  • useFunctions convert structures to JSON format.
  • If serialization fails, the function will returnnil
  • useConvert Go strings to C-compatible strings for passing over JNI.
  1. mainfunction: AlthoughmainThe 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:

  1. Loading the shared library: use("add")Load the shared library generated by Go ()。
  2. Local method statementpublic native String GetPersonJSON();A local method is declared to call the Go function and return a JSON string.
  3. Parse JSON
  • useParses the JSON string returned from the Go function.
  • extractnameandagefield and print to console.
  1. 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:

  1. Compile Go code: Use the following command to compile Go code into a shared library:
go build -o  -buildmode=c-shared 
  1. 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. )

  1. Run Java programs: Run the program with the following command:
java -cp .: GoInvoker
  1. 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!