How can I load a *.java class file into my java app and create an object based on that class file?
You can do it by using classes inside javax.tools. You will have a ToolProvider class from which you can obtain a compiler instance and compile code at runtime. Later you will load .class files just compiled separately with a ClassLoader unless you obtain directly a binary code for the class and you are able to istantiate it directly.
Take a look here
Try Janino's SimpleCompiler. Simple example, assuming you're compiling a class with a public no-arg constructor.
import org.codehaus.janino.SimpleCompiler;
public class JaninoSimpleTest
{
public static void main(String[] args) throws Throwable
{
String filename = args[0];
String className = args[1];
SimpleCompiler compiler = new SimpleCompiler(filename);
ClassLoader loader = compiler.getClassLoader();
Class compClass = loader.loadClass(className);
Object instance = compClass.newInstance();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With