簡體   English   中英

aws lambda java:如何在動態編譯時設置 class 路徑

[英]aws lambda java : How to set the class path while compiling on the fly

我正在構建一個 AWS Lambda function,它可以即時編譯 class。 但是 lambda function 會拋出錯誤,因為它無法找到依賴關系,即即時編譯的 class 的導入語句。 我已經為所遵循的步驟提供了示例代碼。

請指導我如何找到依賴項,即設置 class 路徑,以便動態創建的 class 編譯時不會出現任何錯誤

  1. 正在編譯的示例代碼

    private String constructTestCode(String methodCode) throws Exception{ StringBuffer strMethod = new StringBuffer(); strMethod.append("import org.json.simple.JSONObject;"); strMethod.append("public class TestJavaFile {"); strMethod.append("public void testSample() {"); strMethod.append("JSONObject j = new JSONObject();"); strMethod.append("}"); strMethod.append("}"); return strMethod.toString(); }
  2. Java編譯器代碼

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); List<String> optionList = new ArrayList<String>(); optionList.addAll(Arrays.asList("- classpath",System.getProperty("java.class.path"))); if (compiler == null) { try { Class<?> javacTool = Class.forName("com.sun.tools.javac.api.JavacTool"); Method create = javacTool.getMethod("create"); compiler = (JavaCompiler) create.invoke(null); compiler.getTask(null, null, null, optionList, null, null); } catch (Exception e) { throw new AssertionError(e); } } try { compiler.run(null, null, null, javaFile.toFile().getAbsolutePath()); } catch (Exception e) { context.getLogger().log("Exception " + e + "\n"); } return javaFile.getParent().resolve(fileName + ".class");
  3. Gradle 一胖 jar

     task customFatJar(type: Jar) { manifest { attributes 'Class-Path': configurations.runtime.files.collect { it.name }.join(' ') } baseName = 'all-in-one-jar' from { configurations.compile.collect { it.isDirectory()? it: zipTree(it) } } with jar }
  4. 執行 lambda function 時出錯

    /tmp/TestJavaFile.java:1: error: package org.json.simple does not exist

要編譯的文件保存在 /tmp 目錄中。 我無法確定存在依賴 jar 文件的路徑以及如何在類路徑中設置它。 請對此進行指導。

非常感謝!

這是通過將類路徑設置為解決的

    try {
        StandardJavaFileManager standardJavaFileManager = 
                   compiler.getStandardFileManager(null, null, null);
        standardJavaFileManager.setLocation(StandardLocation.CLASS_PATH, 
                   listFilePaths(folder, context));
        File[] javaFiles = new File[] { javaFile.toFile(), 
        Paths.get("/tmp/JUnitTest.java").toFile() };

        Iterable<? extends JavaFileObject> compilationUnits1 = 
                 standardJavaFileManager
                .getJavaFileObjectsFromFiles(Arrays.asList(javaFiles));
        CompilationTask task = compiler.getTask(null, standardJavaFileManager, null, 
                 optionList, null,
                 compilationUnits1);
        task.call();
       } catch (Exception e) {
           context.getLogger().log("Exception " + e + "\n");
       }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM