Created
January 22, 2017 21:55
-
-
Save Scarsz/c7d2ffde05f2c7ac0c9ee9edb0cac978 to your computer and use it in GitHub Desktop.
Source taken from Sven Furuslätt; https://www.quora.com/How-can-I-dynamically-create-a-Java-class-and-execute-its-methods-at-runtime
This file contains 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
// create an empty source file | |
File sourceFile = File.createTempFile("Hello", ".java"); | |
sourceFile.deleteOnExit(); | |
// generate the source code, using the source filename as the class name | |
String classname = sourceFile.getName().split("\\.")[0]; | |
String sourceCode = "public class " + classname + "{ public void hello() { System.out.print(\"Hello world\");}}"; | |
// write the source code into the source file | |
FileWriter writer = new FileWriter(sourceFile); | |
writer.write(sourceCode); | |
writer.close(); | |
// compile the source file | |
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); | |
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); | |
File parentDirectory = sourceFile.getParentFile(); | |
fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singletonList(parentDirectory)); | |
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Collections.singletonList(sourceFile)); | |
compiler.getTask(null, fileManager, null, null, null, compilationUnits).call(); | |
fileManager.close(); | |
// load the compiled class | |
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { parentDirectory.toURI().toURL() }); | |
Class<?> helloClass = classLoader.loadClass(classname); | |
// call a method on the loaded class | |
Method helloMethod = helloClass.getDeclaredMethod("hello"); | |
helloMethod.invoke(helloClass.newInstance()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment