Advertisement
Guest User

add main

a guest
Jun 24th, 2010
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.84 KB | None | 0 0
  1. // How to use groovy in Java 1.6 with ScriptEngine
  2. // just for POC purposes
  3.  
  4. import javax.script.ScriptContext;
  5. import javax.script.ScriptEngine;
  6. import javax.script.ScriptEngineManager;
  7. import javax.script.ScriptException;
  8. import java.util.Arrays;
  9. import java.util.List;
  10.  
  11.  
  12. class Customer {
  13.     Customer(String name, String code, Integer value) {
  14.         this.name = name;
  15.         this.code = code;
  16.         this.value = value;
  17.     }
  18.  
  19.     String name;
  20.     String code;
  21.     Integer value;
  22. }
  23.  
  24. public class Main {
  25.     public static void main(String[] args) throws ScriptException {
  26.         List<Customer> customers = Arrays.asList( new Customer[]{
  27.            new Customer("A","123",1),
  28.            new Customer("B","456",2),
  29.            new Customer("C","789",3),
  30.            new Customer("D","012",4)
  31.         });
  32.  
  33.         setVariable(customers, "list");
  34.         evaluate("names = list.collect { it.name } ");
  35.         List<String> names = (List<String>) getVariable("names");
  36.         System.out.println("names = " + names);
  37.     }
  38.  
  39.     // Bunch of helper methods, just to make the above code
  40.     // more readable, not necessarily more efficient
  41.  
  42.     private static Object getVariable(String name) {
  43.         return groovy().getContext().getAttribute(name);
  44.     }
  45.  
  46.     private static void evaluate(String script) throws ScriptException {
  47.         groovy().eval(script, groovy().getContext());
  48.     }
  49.  
  50.     private static void setVariable(List<Customer> customers, String varName) {
  51.         groovy().getContext().setAttribute(varName, customers, ScriptContext.ENGINE_SCOPE);
  52.     }
  53.  
  54.     private static ScriptEngine groovyEngine;
  55.     private static ScriptEngine groovy() {
  56.         if( groovyEngine == null  ){
  57.             groovyEngine = new ScriptEngineManager().getEngineByName("Groovy");
  58.         }
  59.         return groovyEngine;
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement