Groovy dynamic analysis

A: need to say something in front of you?

B: do not need it?

A: need it?

 

A way to resolve: to initialize GroovyScriptEngine by the designated paths

//通过指定的paths来初始化GroovyScriptEngine
String[] paths = {"D:\\GroovyScript"};
GroovyScriptEngine gse = new GroovyScriptEngine(paths);

Binding binding = new Binding();
binding.setVariable("input", "world");

gse.run("GroovyDemo.groovy", binding);
System.out.println(binding.getVariable("output"));

GroovyDemo.groovy

output = "Hello ${input}!"

Analytical way: to initialize GroovyScriptEngine by specifying the roots

//通过指定的roots来初始化GroovyScriptEngine
String[] roots = new String[]{"src/com/ccav/javarisk/"};
GroovyScriptEngine gsen = new GroovyScriptEngine(roots);
GroovyObject groovyObject = (GroovyObject) gsen.loadScriptByName("HelloWorld.groovy").newInstance();
String result = (String) groovyObject.invokeMethod("output", "world");
System.out.println(result);

HelloWord.groovy

class TestScript {
    static String output(def str) {
        return "Hello " + str + ", I'm first!";
    }
}

Three ways to resolve: to create a direct instance of engine parse text content

// Create instance directly parsed text engine 
the ScriptEngineManager Factory = new new the ScriptEngineManager (); 

// every time a generating engine example 
the ScriptEngine = factory.getEngineByName engine ( "Groovy" ); 
System.out.println (engine.toString ()); 
Engine the Assert ! = null ; 
Bindings the Binding = engine.createBindings (); 
binding.put ( "DATE", new new a Date ()); 

// if script from a text file, first obtain the contents of the file 
engine.eval ( "def getTime ( ) date.getTime {return ();} " , Binding); 
engine.eval ( " DEF the sayHello (name, Age) {return 'the Hello, the I AM' + name + ', Age' + Age;} " );
Long time = (Long) ((Invocable) engine).invokeFunction("getTime", null);
System.out.println(time);
String message = (String) ((Invocable) engine).invokeFunction("sayHello", "zhangsan", new Integer(12));
System.out.println(message);

 

Guess you like

Origin www.cnblogs.com/wpcnblog/p/10973433.html