2010-01-28 2 views
4

JavaCompiler에서 컴파일 한 프로그램을 실행할 방법이 있습니까? [javax.tools.JavaCompiler]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", " ")); 
    } 

지금 내가 평생 1 초에 그 프로그램을 실행하고 문자열 변수에 출력을 얻을 싶어요. 내가 할 수있는 방법이 있니?

답변

5

당신은 그런 식으로 반사 뭔가를 사용해야합니다 :

// 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); 

사용자의 요구

+0

하지만 프로그램의 수명은 어떻게됩니까? 웹 앱에서 사용했습니다. Java를 배우기위한 Spring 기반의 웹 애플리케이션입니다. 학생이 무한 루프를 만들면 ... – tzim

+0

그런 응용 프로그램을 확보하는 것은 매우 좋은 질문이지만 또한 매우 다른 질문입니다. –

1

당신은 현재의 클래스 패스에 컴파일 된 클래스를 추가 할 필요에 맞게 물론 그것을 적응.

프로젝트를 설정하는 방법에 따라 여러 가지 방법이 있습니다. 여기 이는 java.net.URLClassLoader를 사용하여 하나 개의 인스턴스는 다음과 같습니다

"URL이"파일 시스템을 가리키는 URL 목록입니다
ClassLoader cl_old = Thread.currentThread().getContextClassLoader(); 
ClassLoader cl_new = new URLClassLoader(urls.toArray(new URL[0]), cl_old); 

.