I agree that scripting support adds some flexibility to Java platform development, undoubtly. But I can't see it as a "solution for all your problems" like a lot of people are saying around internet. I think it is a good tool for specific problems. You can use it to solve a problem that you know is easier to solve using that script language you love. But there are shortcomes if you want to use it in a larger scope than that very specific task. I mean: "ok, lets use it, but this is only a nice feature, useful in specific circunstances".
If you want to try scripting capabilities inside your java program, this is the easiest way:
- Create a ScriptEngineManager object.
- Get a ScriptEngine object from the manager.
- Evaluate the script using the ScriptEngine's eval methods.
import javax.script.*;
public class EvalScript {
public static void main(String[] args) throws Exception {
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
// create a Java object
String name = "Tom";
// create the binding
engine.put("greetingname", name);
// evaluate JavaScript code from String
engine.eval("println('Hello, ' + greetingname)");
engine.eval("println('The name length is ' + greetingname.length)");
}
}
You can use Rhino, Quercus, Scala, JRuby, JavaFX, JavaScript and almost any scripting language, including your own language (scripting support is pluggable, so you can write a component to support your own language).Don't use scripting in a performance critical part of your application and always try to use intermediary result, to boost performance (some languages support intermediary compilation, increasing performance).
You can see more at Java Scripting Programmer's Guide, and this article (the example came from there).
0 comments:
Post a Comment