Using Java Classes and Libraries - Java Scripting

Java examples for Scripting:Bindings

Introduction

Javascript source


var oldDate = Java.type("java.util.Date");
var array = Java.type("java.util.ArrayList");
var emp = Java.type("org.yourpkg.Employee");

var empArray = new array();
var emp1 = new emp("A", "C", new oldDate());
var emp2 = new emp("B", "D", new oldDate());
empArray.add(emp1);
empArray.add(emp2);

print(empArray[0]);

empArray.forEach(function(employee, index, ar){
    print("Employee: " + employee);
    print("Hire Date: " + employee.hireDate);
});

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 {
    //from w w  w. j a va 2s .c om
    public static void main(String[] args){

        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine nashorn = sem.getEngineByName("nashorn");
        try {
            nashorn.eval("load('employeeFactory.js');");
        } catch (ScriptException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Result

Employee.java source

Demo Code

import java.util.Date;

class Employee {//from w w  w.j a  va 2  s  .  co  m
  private int age;
  private String first;
  private String last;
  private String position;
  private Date hireDate;

  public Employee() {

  }

  public Employee(String first, String last, Date hireDate) {
    this.first = first;
    this.last = last;
    this.hireDate = hireDate;
  }

  /**
   * @return the age
   */
  public int getAge() {
    return age;
  }

  /**
   * @param age
   *          the age to set
   */
  public void setAge(int age) {
    this.age = age;
  }

  /**
   * @return the first
   */
  public String getFirst() {
    return first;
  }

  /**
   * @param first
   *          the first to set
   */
  public void setFirst(String first) {
    this.first = first;
  }

  /**
   * @return the last
   */
  public String getLast() {
    return last;
  }

  /**
   * @param last
   *          the last to set
   */
  public void setLast(String last) {
    this.last = last;
  }

  /**
   * @return the position
   */
  public String getPosition() {
    return position;
  }

  /**
   * @param position
   *          the position to set
   */
  public void setPosition(String position) {
    this.position = position;
  }

  /**
   * @return the hireDate
   */
  public Date getHireDate() {
    return hireDate;
  }

  /**
   * @param hireDate
   *          the hireDate to set
   */
  public void setHireDate(Date hireDate) {
    this.hireDate = hireDate;
  }

  public String toString() {
    return first + " " + last;
  }

}

Related Tutorials