Java

Prev Next

Available in Classic and VPC

This section describes how to create and use Java actions in a variety of ways, and includes application examples.

Create an action

Creating Java actions is similar to creating JavaScript and Swift actions.

Note

To compile and test actions, JDK 8 must be set up in your local environment.

A Java action is a Java program with a main method. The method must be defined in the following format:

public static com.google.gson.JsonObject main(com.google.gson.JsonObject);

Considering this requirement, here is an example of creating a Java action:

  1. Create a source code file named Hello.java.

    import com.google.gson.JsonObject;
    
    public class Hello {
        public static JsonObject main(JsonObject args) {
            String name = "World";
            String place = "Naver";
            if (args.has("name"))
                name = args.getAsJsonPrimitive("name").getAsString();
            if (args.has("place"))
                place = args.getAsJsonPrimitive("place").getAsString();
    
            JsonObject response = new JsonObject();
            response.addProperty("payload", "Hello, " + name + " in " + place + "!");
            return response;
        }
    }
    
  2. Use the command to compile Hello.java into a JAR file named hello.jar.

    $ javac Hello.java
    
    $ jar cvf hello.jar Hello.class
    
  3. Upload the generated hello.jar file to create an action named helloJava.

cloudfunctions-example-java_v2_01_ko

Main class: Set to Hello class.

If the class is not in the default package, you can use the Java fully-qualified class name (FQCN) including the package, such as com.example.MyMain.

compute-15-2-302_ko

If you want to change the method name of the Java action, you can create an action by specifying a method name like methodName.
compute-15-2-303_ko

Caution

When compiling Java files, google-gson must be included in the Java CLASSPATH.