How do I evaluate a simple script?

The code below will evaluate a simple JavaScript that produces a “Hello World” message. To evaluate the script, the ScriptEngine provides us with some overloaded eval() methods, for instance an eval() methods that accept the script in string or in Reader object.

package org.kodejava.script;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class EvaluatingScript {
    public static void main(String[] args) {
        // Obtaining the GraalVM Javascript engine
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("graal.js");

        try {
            // Evaluating a simple script
            engine.eval("print('Hello World')");
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.graalvm.js</groupId>
        <artifactId>js</artifactId>
        <version>22.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.graalvm.js</groupId>
        <artifactId>js-scriptengine</artifactId>
        <version>22.3.2</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I create an instance of ScriptEngine class for JavaScript?

This example demonstrates how to create a JavaScript interpreter or the ScriptEngine to run JavaScript in Java. The classes related to scripting is packaged under the javax.script.* package. In this example we show you how to create the JavaScript engine by using the engine extension.

package org.kodejava.script;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class GettingJavaScriptEngine {
    public static void main(String[] args) {
        // Creating an instance of ScriptManager. With ScriptManager in hand we
        // can create an interpreter or ScriptEngine to run JavaScript.
        ScriptEngineManager manager = new ScriptEngineManager();

        // Calling manager.getEngineByExtension("js") returns a ScriptEngine
        // implementation for JavaScript engine.
        ScriptEngine engine = manager.getEngineByExtension("js");

        // Do something with the script engine.
        System.out.println("Engine = " + engine);
    }
}

The output of the code snippet:

Engine = com.oracle.truffle.js.scriptengine.GraalJSScriptEngine@56235b8e

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.graalvm.js</groupId>
        <artifactId>js</artifactId>
        <version>22.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.graalvm.js</groupId>
        <artifactId>js-scriptengine</artifactId>
        <version>22.3.2</version>
    </dependency>
</dependencies>

Maven Central Maven Central

How do I get the last element of SortedSet?

package org.kodejava.util;

import java.util.SortedSet;
import java.util.TreeSet;

public class LastSetElement {
    public static void main(String[] args) {
        SortedSet<String> numbers = new TreeSet<>();
        numbers.add("One");
        numbers.add("Two");
        numbers.add("Three");
        numbers.add("Four");
        numbers.add("Five");

        // SortedSet orders the items it contains. We can get the last
        // item from the set using the last() method. The last item 
        // will be "Two".
        String lastElement = numbers.last();
        System.out.println("lastElement = " + lastElement);
    }
}

How do I get the first element of SortedSet?

package org.kodejava.util;

import java.util.TreeSet;
import java.util.SortedSet;

public class FirstSetElement {
    public static void main(String[] args) {
        SortedSet<String> numbers = new TreeSet<>();
        numbers.add("One");
        numbers.add("Two");
        numbers.add("Three");
        numbers.add("Four");
        numbers.add("Five");

        // SortedSet orders the items it contains. We can get the first
        // item from the SortedSet using the first() method. The fist item 
        // will be "Five".
        String firstElement = numbers.first();
        System.out.println("firstElement = " + firstElement);
    }
}

How do I get all annotations?

To obtains all annotations for classes, methods, constructors, or fields we use the getAnnotations()method. This method returns an array of Annotation

In the following example we tried to read all annotations from the sayHi() method. First we need to obtain the method object itself. Because the sayHi() method has parameters, we need to pass not only the method name to the getMethod() method, but we also need to pass the parameter’s type.

The getAnnotations() method returns only annotation that has a RetentionPolicy.RUNTIME, because other retention policy doesn’t allow the annotation to available at runtime.

package org.kodejava.lang.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class GetAllAnnotation {
    private final Map<String, String> data = new HashMap<>();

    public static void main(String[] args) {
        GetAllAnnotation demo = new GetAllAnnotation();
        demo.sayHi("001", "Alice");
        demo.sayHi("004", "Malory");

        try {
            Class<? extends GetAllAnnotation> clazz = demo.getClass();

            // To get the sayHi() method we need to pass not only the method
            // name but also its parameters type so the getMethod() method
            // return the correct method for us to use.
            Method method = clazz.getMethod("sayHi", String.class, String.class);

            // Get all annotations from the sayHi() method. But this actually
            // will only return one annotation. Because only the HelloAnnotation
            // annotation that has RUNTIME retention policy, which means that
            // the other annotations associated with sayHi() method is not
            // available at runtime.
            Annotation[] annotations = method.getAnnotations();
            for (Annotation annotation : annotations) {
                System.out.println("Type: " + annotation.annotationType());
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    @MyAnnotation("Hi")
    @HelloAnnotation(value = "Hello", greetTo = "Everyone")
    public void sayHi(String dataId, String name) {
        Map<String, String> data = getData();
        if (data.containsKey(dataId)) {
            System.out.println("Hello " + data.get(dataId));
        } else {
            data.put(dataId, name);
        }
    }

    private Map<String, String> getData() {
        data.put("001", "Alice");
        data.put("002", "Bob");
        data.put("003", "Carol");
        return data;
    }
}
package org.kodejava.lang.annotation;

public @interface MyAnnotation {
    String value();
}

Check the HelloAnnotation on the following link How do I create a simple annotation?.

The result of this code snippet:

Hello Alice
Type: interface org.kodejava.lang.annotation.HelloAnnotation