You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否通过JShell API替代BeanShell实现应用扩展及脚本方法调用?

Using JShell API to Load Scripts and Invoke Methods (No Command Line)

Absolutely! JShell's built-in API lets you replicate the exact workflow you're using with BeanShell—loading scripts, accessing their methods, and invoking them directly from your Java application, no command line required. It's a clean, JDK-native alternative that integrates smoothly with your existing code.

Here's a practical, step-by-step example to show you how it works:

Step 1: Set Up the JShell Instance

First, create a JShell instance (use try-with-resources to ensure it's properly closed when done):

import jdk.jshell.JShell;
import jdk.jshell.MethodSnippet;
import java.util.Optional;

public class JShellMethodInvocation {
    public static void main(String[] args) {
        try (JShell jshell = JShell.create()) {
            // Your script loading and method invocation code goes here
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Step 2: Load Your Script

You can load script content directly as a string, or read it from a file. For this example, we'll define a simple script with two methods:

// Load script content (replace with Files.readString(Paths.get("your-script.jsh")) for file-based scripts)
String scriptContent = """
    public String greet(String name) {
        return "Hello, " + name + " from JShell!";
    }

    public int calculateSum(int a, int b) {
        return a + b;
    }
    """;

// Evaluate the script to register the methods in JShell
jshell.eval(scriptContent);

Step 3: Locate the Method You Want to Invoke

Use JShell's methods() method to retrieve all registered methods, then filter to find the one you need:

// Find the "greet" method
Optional<MethodSnippet> greetMethod = jshell.methods()
        .stream()
        .filter(method -> method.name().equals("greet"))
        .findFirst();

// Find the "calculateSum" method
Optional<MethodSnippet> sumMethod = jshell.methods()
        .stream()
        .filter(method -> method.name().equals("calculateSum"))
        .findFirst();

Step 4: Invoke the Method

Use JShell.invoke() to execute the method, passing in your arguments. This works similarly to BeanShell's BshMethod.invoke():

// Invoke the greet method
greetMethod.ifPresent(method -> {
    try {
        Object greetResult = jshell.invoke(method, "Alice");
        System.out.println(greetResult); // Output: Hello, Alice from JShell!
    } catch (Exception e) {
        System.err.println("Failed to invoke greet method: " + e.getMessage());
    }
});

// Invoke the calculateSum method
sumMethod.ifPresent(method -> {
    try {
        Object sumResult = jshell.invoke(method, 10, 20);
        System.out.println(sumResult); // Output: 30
    } catch (Exception e) {
        System.err.println("Failed to invoke calculateSum method: " + e.getMessage());
    }
});

Key Notes & Tips

  • Public Methods: Ensure your script methods are marked public—JShell won't expose non-public methods via the API.
  • Classpath Dependencies: If your script relies on external libraries, add them to JShell's classpath using jshell.addToClasspath("path/to/your/library.jar").
  • Type Safety: JShell will validate argument types at invocation time, so you'll get clear exceptions if you pass mismatched parameters (unlike some dynamic scripting tools).
  • Cleanup: Always use try-with-resources for the JShell instance to avoid resource leaks.

This approach gives you the same flexibility as BeanShell, but with the benefit of being part of the core JDK (no extra dependencies needed) and better integration with modern Java features.

内容的提问来源于stack exchange,提问作者Ickbinet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:34:56