Last active
August 29, 2015 14:03
-
-
Save pietrom/c20d0df54d0ba2c4d6c1 to your computer and use it in GitHub Desktop.
Compile, instantiate and use a Java class from source code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.amicofragile.etude.compiling; | |
import java.io.File; | |
import java.io.FileWriter; | |
import java.net.URL; | |
import java.net.URLClassLoader; | |
import javax.tools.JavaCompiler; | |
import javax.tools.ToolProvider; | |
import org.junit.Assert; | |
import org.junit.Test; | |
public class CompileTest { | |
public static interface Hello { | |
public abstract String sayHello(); | |
} | |
@Test | |
public void compileAndExecuteSource() throws Exception { | |
final String src = "package test; public class Test implements org.amicofragile.etude.compiling.CompileTest.Hello {" + | |
"public String sayHello() { return \"Hello, World!\";}" + | |
"}"; | |
final File tempDir = new File(System.getProperty("java.io.tmpdir") + "/sources"); | |
final File pkg = new File(tempDir, "test"); | |
pkg.mkdirs(); | |
final File source = new File(pkg, "Test.java"); | |
new FileWriter(source).append(src).close(); | |
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); | |
compiler.run(null, null, null, source.getPath()); | |
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { tempDir.toURI().toURL() }); | |
Class<Hello> cls = (Class<Hello>) Class.forName("test.Test", true, classLoader); | |
Hello hello = cls.newInstance(); | |
Assert.assertEquals("Hello, World!", hello.sayHello()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment