2017-02-01 3 views
0

편집기가있는 JavaFX 앱이 있습니다. 편집기에서 사용자는 자바 코드를 작성할 수 있으며이 코드를 컴파일하고 main 메소드를 실행하는 버튼이 있습니다. 예를 들어 에디터가이 코드가 포함됩니다 :반사가 제대로 작동하지 않는 Java 런타임 컴파일러

public class Test { 
    public static void main(String[] args) { 
     System.out.println("hello"); 
    } 
} 

클릭에 버튼을,이 코드를 실행합니다 :

public class CodeCompiler { 

public String className; 
public String code; 

public void set(String code) { 
    try { 
     this.className = code.substring(code.indexOf(" class ") + 6, code.indexOf(" {")).trim(); 
    } catch(StringIndexOutOfBoundsException e) { 

    } 
    this.code = code; 
} 

public void createFile() throws IOException { 
    PrintWriter pw = new PrintWriter("speech2code/src/main/java/" + className + ".java"); 
    pw.close(); 
    FileWriter writer = new FileWriter("speech2code/src/main/java/" + className + ".java", true); 
    writer.write(code); 
    writer.flush(); 
    writer.close(); 
} 

public void compile() { 
    File file = new File("speech2code/src/main/java/" + className + ".java"); 
    File classFile = new File("speech2code/src/main/java/" + className + ".class"); 
    classFile.delete(); // delete class file f it exists 
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 
    compiler.run(null, null, null, file.getPath()); 
} 

public void run() { 

    Class<?> cls = null; 
    try { 
     cls = Class.forName(className); 
     System.out.println(cls == null); 
    } catch (ClassNotFoundException e) { 
     e.printStackTrace(); 
    } 
    Method meth = null; 
    try { 
     meth = cls.getMethod("main", String[].class); 
    } catch (NoSuchMethodException e) { 
     e.printStackTrace(); 
    } 
    String[] params = null; 
    try { 
     meth.invoke(null, (Object) params); 
    } catch (IllegalAccessException e) { 
     e.printStackTrace(); 
    } catch (InvocationTargetException e) { 
     e.printStackTrace(); 
    } 

} 


} 
: 컴파일러 클래스에서

runButton.setOnAction(e -> { 
     compiler.set(editor.getText()); 
     try { 
      compiler.createFile(); 
     } catch (IOException e1) { 
      e1.printStackTrace(); 
     } 
     compiler.compile(); 
     compiler.run(); 

    }); 

를, 다음의 구현이

위의 코드는 Java 파일, 클래스 파일을 성공적으로 생성하고 처음 올바르게 실행됩니다. 이제 편집기 코드를 변경하여 다른 것을 인쇄하면 코드가 처음 실행 된 결과가 출력됩니다. 따라서이 경우 현재 값이 아닌 'hello'가 계속 출력됩니다.

어떤 문제가있을 수 있습니까? 감사합니다.

답변

0

새 클래스에 대한 새 클래스 로더를 만들어야합니다. 클래스를 컴파일했기 때문에 클래스가 다시로드되지 않습니다.

URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] {classFile}); 

그럼 당신은 클래스에이 로더를 요청할 수 있습니다 :

Class<?> cls = Class.forName(className, true, classLoader); 
관련 문제