2015년 5월 13일 수요일

Java code에서 java 파일 생성 후 컴파일 하기


package junit_sample;

public class JavaCompileTest {
    @SuppressWarnings("resource")
    public static void main(String[] args) throws Exception {
        // Prepare source somehow.
        String source = "package test; public class Test { " +
                "static { System.out.println(\"hello\"); } " +
                "public Test() { System.out.println(\"world\"); } }";

        // Save source in .java file.
        File root = new File("/java"); // On Windows running on C:\, this is C:\java.
        File sourceFile = new File(root, "test/Test.java");
        sourceFile.getParentFile().mkdirs();

        System.out.println("path: " + sourceFile.getParentFile());

        new FileWriter(sourceFile).append(source).close();

        // Compile source file.
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        compiler.run(null, null, null, sourceFile.getPath());

        // Load and instantiate compiled class.
        URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });
        Class<?> cls = Class.forName("test.Test", true, classLoader); // Should print "hello".
        Object instance = cls.newInstance(); // Should print "world".
        System.out.println(instance); // Should print "test.Test@hashcode".
    }
}

댓글 없음:

댓글 쓰기