Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Get values from java script function ?

807580Mar 10 2010 — edited Mar 10 2010
I need to call a function in a .js file from my java application and get the result :


import java.io.File;
import java.net.URL;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class TT {

 
  
  public static void main(String[] args) throws Exception {
    
    // create a script engine manager
    ScriptEngineManager factory = new ScriptEngineManager();
    // create JavaScript engine
    ScriptEngine engine = factory.getEngineByName("JavaScript");

    // evaluate JavaScript code from given file - specified by first argument
    engine.eval(new java.io.FileReader(args[0]));
    engine.eval(new java.io.FileReader(jsFile)); 
    
    
    // javax.script.Invocable is an optional interface.
    // Check whether your script engine implements or not!
    // Note that the JavaScript engine implements Invocable interface.
    Invocable inv = (Invocable) engine;
    
    Object obj = engine.get("obj");
    
    // invoke the method named "hello" on the script object "obj"    
    inv.invokeMethod(obj, "hello", "2" );
    
  }
}
where the script do:
var obj = new Object();
obj.hello = function(name) {
	var v  = parseFloat(name);
        return v + 100;
}
But how do I read this return value in my java app?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 7 2010
Added on Mar 10 2010
5 comments
864 views