java - 在 Janino 中从字符串编译 Lambda 表达式
问题描述
我正在尝试使用 Janino 从字符串编译一个类。该类在函数内包含一个 lambda 表达式,但它似乎无法识别引用运算符“->”和“::”。
我得到一个 CompileException 线程“主”org.codehaus.commons.compiler.CompileException 中的完整股权跟踪异常:第 1 行,第 346 列:主中的意外令牌“>”
下面是我正在使用的代码,
public class LambdaFromJanino{
public static void main(String[] args) throws Exception
{
String CLASS_NAME = "Foo";
String codeStr = "import java.util.Arrays;" +
"import java.util.List;"+
"import java.util.stream.Collectors;"+
"public class " + CLASS_NAME + " {" +
"public static void main(String[] args) {" +
"System.out.println(\"Hello \" + args[0]);" +
"List<String> result = lambdaOut(args);"+
//"result.forEach(System.out::println);"+
"System.out.println(\"this is result \"+result.get(0));"+
"}" +
"static List lambdaOut(String[] arr) { " +
"return Arrays.stream(arr).map( x -> x.replaceAll(\"[a-zA-Z]\", \"\"))" +
".collect(Collectors.toList()); }; " +
"}";
SimpleCompiler compiler = new SimpleCompiler();
compiler.cook( codeStr ); // compile the string
// get the loaded class
Class<?> cl = compiler.getClassLoader().loadClass(CLASS_NAME);
// Invoke the "public static main(String[])" method
Method mainMeth = cl.getMethod("main", new Class[] { String[].class });
String[] methArgs = new String[] { args[0], args[1], args[2] }; // one input
mainMeth.invoke(null, new Object[] { methArgs });
}
}
解决方案
试试下面的代码,它将有助于解决您的问题。
因为你不是收集结果我的 lambda 表达式,所以我附上\"\")).collect(Collectors.toList())\n"
来解决它。
public static void main(String[] args) throws Exception
{
String CLASS_NAME = "Foo";
String codeStr = "import java.util.Arrays;" +
"import java.util.List;"+
"import java.util.stream.Collectors;"+
"public class " + CLASS_NAME + " {" +
"public static void main(String[] args) {" +
"System.out.println(\"Hello \" + args[0]);" +
"List<String> result = lambdaOut(args);"+
//"result.forEach(System.out::println);"+
"System.out.println(\"this is result \"+result.get(0));"+
"}" +
"static List lambdaOut(String[] arr) { " +
"return Arrays.stream(arr).map( x -> x.replaceAll(\"[a-zA-Z]\", \"\")).collect(Collectors.toList())\n" +
".collect(Collectors.toList()); }; \n" +
"}";
推荐阅读
- apache-spark - Azure Synapse“覆盖”方法中的 Apache Spark 功能不起作用
- ruby-on-rails - 在 Ransack 中过滤数组的第一个元素
- r - 如何为 geojson 矢量地图添加额外的数据特征?
- sql - 无法理解 Laravel“获取列名”函数输出
- database - 我可以对需要 3 列来唯一标识 dynamodb 中的行的数据进行建模吗?
- visual-studio - 未添加断点 blazor wasm 项目 Visual Studio 2019 16.10.1 sdk 5.0.301
- python - 如何在 Python 中生成动态请求标头?
- r - 如何获得R中向量元素的所有组合?
- javascript - 基于 ActionScript XMLsocket 的 JavaScript Websocket
- laravel - 如何将 ZipStream 与 Larvel 8.x 控制器一起使用,然后重定向