Implementing Java Interfaces - Java Scripting

Java examples for Scripting:Bindings

Introduction

Javascript Source

var somePosition = new org.my.chapter18.recipe18_08.PositionType({
  hourlyWage: function(hours, wage){
      return hours * wage;
  }
});

print(somePosition instanceof Java.type("org.my.chapter18.recipe18_08.PositionType"));
var bigDecimal = Java.type("java.math.BigDecimal");

print(somePosition.hourlyWage(new bigDecimal(40), new bigDecimal(12.75)));

Java Source

Demo Code

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;


public class Main {
    public static void main(String[] args){
        loadAndRun();/* w ww. ja  v a 2  s .c om*/
    }
    
    public static void loadAndRun(){
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine nashorn = sem.getEngineByName("nashorn");
        try {
            nashorn.eval("load('/js/test.js');");
        } catch (ScriptException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Result

interface file

Demo Code

import java.math.BigDecimal;

public interface PositionType {
    /*from   w  w  w  .  j a  v a  2s.c om*/
    public double hourlyWage(BigDecimal hours, BigDecimal wage);
    
    default public BigDecimal yearlySalary(BigDecimal wage){
        return (wage.multiply(new BigDecimal(40))).multiply(new BigDecimal(52));
    }
}

Related Tutorials