Java Reference
In-Depth Information
that it does not understand the meaning of the variable
msg
. This is where the concept of
passing parameters from a Java program to a script engine comes into play.
You can pass a parameter to a script engine in several ways. The simplest way is
to use the
put(String paramName, Object paramValue)
method of the script engine,
which accepts two arguments:
The first argument is the name of the parameter, which needs to
•
match the name of the variable in the script.
•
In your case, you want to pass a parameter named
msg
to the script engine and its
value is a
String
. The call to the
put()
method is:
The second argument is the value of the parameter.
// Store the value of the msg parameter in the engine
engine.put("msg", "Hello from Java program");
Note that you must call the
put()
method of the engine before calling the
eval()
method. In your case, when the engine attempts to execute
print(msg)
, it will use the
value of the
msg
parameter that you passed to the engine.
Most script engines let you use the parameter names that you pass to it as the
variable name in the script. You saw this kind of example when you passed the value of
the parameter named
msg
and used it as a variable name in the script in Listing 2-3.
A script engine may have a requirement for declaring variables in scripts, for example, a
variable name must start with a $ prefix in PHP and a global variable name contains a $
prefix in JRuby. If you want to pass a parameter named
msg
to a script in JRuby, your code
would be as shown:
// Get the JRuby script engine
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("jruby");
// Must use the $ prefix in JRuby script
String script = "puts($msg)";
// No $ prefix used in passing the msg parameter to the JRuby engine
engine.put("msg", "Hello from Java");
// Execute the script
engine.eval(script);
Properties and methods of Java objects passed to scripts can be accessed in scripts,
as they are accessed in Java code. Different scripting languages use different syntax to
access Java objects in scripts. For example, you can use the expression
msg.toString()
in the example shown in Listing 2-3 and the output will be the same. In this case, you are
Search WWH ::
Custom Search