script

Modify Java object in script

Photo of Byron KiourtzoglouByron KiourtzoglouNovember 11th, 2012Last Updated: October 2nd, 2013
0 116 2 minutes read

With this example we are going to demonstrate how to modify a Java object in script. In short, to modify a Java object using script we have followed the steps below:

  • Create a newScriptEngineManager. The ScriptEngineManager implements a discovery and instantiation mechanism for ScriptEngine classes and also maintains a collection of key/value pairs storing state shared by all engines created by the Manager.
  • Use thegetEngineByExtension(String extension) API method to look up and create aScriptEngine for the js extension.
  • Useput(String key, Object value) API method of ScriptEngine to set a key/value pair in the state of the ScriptEngine that may either create a Java Language Binding to be used in the execution of scripts or be used in some other way, depending on whether the key is reserved. The value set here is a list of String car names, with the key"brandList".
  • Create a new String script to print the list and then add new elements in the list.
  • Use theeval(String script) method to execute the script.
  • After executing the script print the list elements again. The list now has the new elements added to it by the script.

Let’s take a look at the code snippet that follows:  

package com.javacodegeeks.snippets.core;import javax.script.ScriptEngineManager;import javax.script.ScriptEngine;import javax.script.ScriptException; import javax.script.ScriptEngineManager;import javax.script.ScriptEngine;import javax.script.ScriptException;import java.util.Date;import java.util.List;import java.util.ArrayList; public class ModifyObjectFromScript {    public static void main(String[] args) {  // Create a List of car brands  List<String> brands = new ArrayList<String>();  brands.add("Audi");  brands.add("Mercedes");  brands.add("Renault");  brands.add("Ford");  brands.add("Seat");  // Obtain a ScriptEngine instance  ScriptEngineManager manager = new ScriptEngineManager();  ScriptEngine engine = manager.getEngineByExtension("js");   // Set List into the engine  engine.put("brandList", brands);  try {engine.eval(getScript());// Redisplay the modified version of brands list object.for (String brand : brands) {    System.out.println("Brand = " + brand);}  } catch (ScriptException e) {e.printStackTrace();  }    }     private static String getScript() {    // Script that reads and adds brands   String script =    "var index; " +    "var brands = brandList.toArray(); " +    " " +    "for (index in brands) { " +    "    println(brands[index]); " +    "}" +    " " +    "brandList.add("BMW"); " +    "brandList.add("KIA"); " +    "brandList.add("Smart"); ";  return script;    }}

Output:

AudiMercedesRenaultFordSeatBrand = AudiBrand = MercedesBrand = RenaultBrand = FordBrand = SeatBrand = BMWBrand = KIABrand = Smart

  
This was an example of how to modify a Java object in script in Java.

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Byron KiourtzoglouByron KiourtzoglouNovember 11th, 2012Last Updated: October 2nd, 2013
0 116 2 minutes read
Photo of Byron Kiourtzoglou

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor atJava Code Geeks.

Related Articles

Bipartite Graph

Get script engine by name

November 11th, 2012
Bipartite Graph

Import package in script

November 11th, 2012
Bipartite Graph

Evaluate a simple script

November 11th, 2012
Bipartite Graph

Evaluate a script file

November 11th, 2012
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.