كيف يتم تشغيل التعليمات البرمجية التي جمعتها Javacompiler؟

StackOverflow https://stackoverflow.com/questions/2156842

  •  23-09-2019
  •  | 
  •  

سؤال

هل هناك أي طريقة لتشغيل البرنامج الذي جمعته Javacompiler؟ [javax.tools.javacompiler

رمز بلدي:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, prepareFile(nazwa, content));
    task.call();

    List<String> returnErrors = new ArrayList<String>();
    String tmp = new String();
    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
        tmp = String.valueOf(diagnostic.getLineNumber());
        tmp += " msg: "+ diagnostic.getMessage(null);
        returnErrors.add(tmp.replaceAll("\n", " "));
    }

الآن أريد تشغيل هذا البرنامج مع Lifetime 1 Sec والحصول على الإخراج إلى متغير السلسلة. هل هناك أي طريقة يمكنني فعل ذلك؟

هل كانت مفيدة؟

المحلول

تحتاج إلى استخدام التفكير ، شيء من هذا القبيل:

// Obtain a class loader for the compiled classes
ClassLoader cl = fileManager.getClassLoader(CLASS_OUTPUT);
// Load the compiled class
Class compiledClass = cl.loadClass(CLASS_NAME);
// Find the eval method
Method myMethod = compiledClass.getMethod("myMethod");
// Invoke it
return myMethod.invoke(null);

قم بتكييفه بالطبع لتناسب احتياجاتك

نصائح أخرى

يجب عليك إضافة الفئة المترجمة إلى ClassPath الحالي.

هناك عدد من الطرق للقيام بذلك ، اعتمادًا على كيفية إعداد مشروعك. إليك مثيل واحد باستخدام java.net.urlclassloader:

ClassLoader cl_old = Thread.currentThread().getContextClassLoader();
ClassLoader cl_new = new URLClassLoader(urls.toArray(new URL[0]), cl_old);

حيث "urls" هي قائمة عناوين URL التي تشير إلى نظام الملفات.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top