Hi,
How can I load a *.java class file into my java app and create an object based on that class file?
Hi,
How can I load a *.java class file into my java app and create an object based on that class file?
You cannot. The .java file needs to be compiled into a .class so that you can use it.
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();
}
}