【发布时间】:2020-12-09 18:17:12
【问题描述】:
我正在尝试使用 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 });
}
}
【问题讨论】:
-
您确定您使用的是 Java 8 或更高版本吗?
-
是的,我使用的是 Java 8,当直接在 main 方法中调用时,这个 lambda 表达式可以正常工作。
-
问题不在于 Lambda 表达式,而在于
List<String> result的赋值。 -
即使你尝试这样的静态,它也不起作用
List<String> result= new ArrayList<String>(); -
@SagarGangwal List
结果= new ArrayList ();工作正常只需要添加“import java.util.ArrayList;”在进口。因此,如果我只返回函数 lambdaOut 中的列表而不使用任何 lambda 表达式,它就可以正常工作。
标签: java compiler-construction janino java-runtime-compiler