Implementing an interface from script

suggest change
import java.io.FileReader;
import java.io.IOException;

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

public class InterfaceImplementationExample {
    public static interface Pet {
        public void eat();
    }

    public static void main(String[] args) throws IOException {
        // Nashorn was included in Java 8 through 14 and removed in Java 15.
        // getEngineByName returns null when it is absent; eval then throws NullPointerException.
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("nashorn");

        try {
            // pet.js is a file in the working directory, not the comment below.
            // The binary name of the nested type uses '$', not '.'.
            /*
                var Pet = Java.type("InterfaceImplementationExample$Pet");

                new Pet() {
                    eat: function() { print("eat"); }
                }
            */
            
            Pet pet = (Pet) engine.eval(new FileReader("pet.js"));
            
            pet.eat();
        } catch (ScriptException ex) {
            ex.printStackTrace();
        }

        // Outcome:
        // 'eat' printed on standard output
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents