方案一:
https://vimsky.com/examples/detail/java-class-javax.script.Invocable.html
import javax.script.Invocable; //导入依赖的package包/类
public Object executeJs(String js,@Nullable String funcName,Object... args){
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
try {
Object res=engine.eval(js);
if(StringUtils.isNotBlank(funcName)){
if (engine instanceof Invocable) {
Invocable invoke = (Invocable) engine;
res = invoke.invokeFunction(funcName, args);
}
}
return res;
} catch (Exception e) {
log.error("",e);
}
return null;
}
方案二
https://www.jb51.net/article/209651.htm
1.导包
org.apache.commons commons-jexl3 3.2.1
2、demo实例
private String condition(){
// 用于存储参数
MapContext context = new MapContext();
context.set("strA",1);
context.set("strB",2);
// 动态脚本(里面的参数都需要存储在context)
String condition = "strA <= strB ? \"yes\" : \" No\"";
JexlExpression expression = new Engine().createExpression(condition );
return expression .evaluate(context).toString();
}
@Test
private void test(){
String condition = condition();
System.out.println(condition);
}