杰瑞科技汇

scriptengine java

Of course! Let's break down ScriptEngine in Java, which is a core part of the Java Scripting API (JSR-223).

scriptengine java-图1
(图片来源网络,侵删)

What is ScriptEngine?

In simple terms, ScriptEngine is an interface in the Java standard library that acts as a bridge between your Java application and a scripting language (like JavaScript, Python, Ruby, Groovy, etc.).

Think of it as a universal remote control. You don't need to know the specific details of how each TV (scripting engine) works. You just use the standard buttons (eval, put, get) on the remote, and it translates your commands to the specific TV's language.

This allows you to execute code written in a scripting language directly from within your Java application, enabling powerful features like:

  • Dynamic Scripting: Run user-provided scripts or configurations.
  • Extensibility: Let users extend your application's functionality with scripts without recompiling the main Java code.
  • Rapid Prototyping: Quickly test ideas using a more flexible scripting language.

The Core Components of the Java Scripting API

To understand ScriptEngine, you need to know its supporting classes and interfaces, all located in the javax.script package:

scriptengine java-图2
(图片来源网络,侵删)
  1. ScriptEngine: The main interface. It defines the basic methods for executing scripts, managing variables, and getting results.
  2. ScriptEngineManager: The factory class. Its job is to discover, load, and instantiate ScriptEngine implementations. You ask the manager for an engine, and it finds one for you.
  3. Bindings: A simple interface for storing key-value pairs. It's used to share data between your Java application and the script.
  4. ScriptContext: A more advanced way to manage the execution environment of a script. It can have multiple scopes (like ENGINE_SCOPE for engine-specific variables and GLOBAL_SCOPE for variables shared across all engines) and define the input, output, and error readers/writers for the script.

How to Use ScriptEngine: A Step-by-Step Example

Let's use the most common example: executing JavaScript from Java. Java comes bundled with a JavaScript engine (Nashorn).

Step 1: Get a ScriptEngine Instance

You don't create the engine directly. You use the ScriptEngineManager.

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
public class SimpleScript {
    public static void main(String[] args) {
        // 1. Create a ScriptEngineManager
        ScriptEngineManager manager = new ScriptEngineManager();
        // 2. Get a ScriptEngine instance. We ask for "js" for JavaScript.
        // The manager will find and return the appropriate engine.
        ScriptEngine engine = manager.getEngineByName("js");
        // Check if the engine was found
        if (engine == null) {
            System.out.println("No JavaScript engine found!");
            return;
        }
        System.out.println("Successfully obtained JavaScript engine: " + engine.getClass().getName());
    }
}

Step 2: Execute Simple Script Code

The most basic operation is eval(), which evaluates a string of script code.

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class SimpleScript {
    public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        if (engine == null) {
            System.out.println("No JavaScript engine found!");
            return;
        }
        try {
            // 3. Execute a simple script string
            System.out.println("--- Executing Simple Script ---");
            engine.eval("println('Hello from JavaScript!');");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

scriptengine java-图3
(图片来源网络,侵删)
Successfully obtained JavaScript engine: jdk.nashorn.api.scripting.NashornScriptEngine
--- Executing Simple Script ---
Hello from JavaScript!

Step 3: Pass Variables Between Java and the Script

You can use the put() method to pass variables from Java to the script and get() to retrieve them.

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class VariablePassing {
    public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        try {
            // 1. Put a variable into the script's scope
            engine.put("name", "Java Developer");
            engine.put("age", 30);
            // 2. Execute a script that uses these variables
            engine.eval("var greeting = 'Hello, ' + name + '!';");
            engine.eval("println(greeting);");
            engine.eval("println('You are ' + age + ' years old.');");
            // 3. Get a result back from the script
            // Note: Nashorn returns a String for the last evaluated expression
            Object result = engine.eval("age * 2;");
            System.out.println("The script calculated: " + result); // Prints 60
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

Hello, Java Developer!
You are 30 years old.
The script calculated: 60

Step 4: Call Java Methods from the Script

This is a very powerful feature. The script can not only use variables you provide but also call methods from your Java classes.

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class JavaFromScript {
    public static void main(String[] args) {
        ScriptEngineManager manager = new JavaScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        try {
            // 1. Define a static method in a Java class
            // For this example, let's assume this method exists in a class named Utils
            // public static String formatDate(String input) { ... }
            // 2. Execute a script that calls this Java method
            // We use the full class name to access the static method
            engine.eval("var formattedDate = javax.script.SimpleScript.formatDate('2025-10-27');");
            engine.eval("println('Formatted Date: ' + formattedDate);");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // A simple utility method for the example
    public static String formatDate(String input) {
        // A very basic "formatting" logic
        return input.replace('-', '/');
    }
}

Output:

Formatted Date: 2025/10/27

Other Important Methods in ScriptEngine

Method Description
eval(String script) Evaluates the script string.
eval(Reader reader) Evaluates the script read from a Reader (e.g., from a file).
put(String key, Object value) Adds a variable to the script's ENGINE_SCOPE.
get(String key) Retrieves a variable from the script's ENGINE_SCOPE.
getBindings(int scope) Gets the Bindings object for a specific scope (e.g., ScriptContext.ENGINE_SCOPE).
setBindings(Bindings bindings, int scope) Sets the Bindings for a specific scope.

Popular Scripting Engines for Java

While Nashorn (JavaScript) is built-in, you can add others to your project.

Scripting Language Popular Engine Maven Dependency
JavaScript Nashorn (built-in since Java 8), GraalVM -
Python Jython org.python:jython-standalone
Groovy Groovy org.apache.groovy:groovy
Ruby JRuby org.jruby:jruby
Kotlin Kotlin Scripting org.jetbrains.kotlin:kotlin-scripting-jvm

To use a different engine, you just need to have its JAR on your classpath, and the ScriptEngineManager will automatically find it.

// Example for getting a Groovy engine
ScriptEngine groovyEngine = manager.getEngineByName("groovy");

Key Takeaways

  1. ScriptEngine is an Interface: It's the standard contract for any scripting language integration in Java.
  2. ScriptEngineManager is the Factory: It's the entry point for getting an instance of a script engine.
  3. It's a Two-Way Street: You can pass data to scripts (put) and get results back (get).
  4. Scripts Can Call Java: This allows for deep integration and extensibility.
  5. JSR-223 is Standard: This API is part of the Java SE platform, making it a portable and reliable way to add scripting capabilities.
分享:
扫描分享到社交APP
上一篇
下一篇