在Janino中从String编译Lambda表达式

问题描述

我正在尝试使用Janino从String编译一个类。该类在函数内部包含一个lambda表达式,但似乎无法识别引用运算符“->”和“ ::”。

我收到了CompileException 完整的股权追踪 线程“ main” 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" +
                    "}";