如何将* .java类文件加载到我的java应用程序中并根据该类文件创建一个对象?
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();
}
}
我认为这会有所帮助: Package Summary或Simple Comipler 。
You cannot. The .java file needs to be compiled into a .class so that you can use it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.