简体   繁体   English

从外部java文件创建Java对象

[英]Create Java object from external java file

如何将* .java类文件加载到我的java应用程序中并根据该类文件创建一个对象?

You can do it by using classes inside javax.tools . 您可以使用javax.tools类来完成。 You will have a ToolProvider class from which you can obtain a compiler instance and compile code at runtime. 您将拥有一个ToolProvider类,您可以从中获取编译器实例并在运行时编译代码。 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. 稍后您将加载仅使用ClassLoader单独编译的.class文件,除非您直接获得该类的二进制代码,并且您可以直接对其进行异步处理。

Take a look here 看看这里

Try Janino's SimpleCompiler . 试试Janino的SimpleCompiler Simple example, assuming you're compiling a class with a public no-arg constructor. 简单的例子,假设您正在使用public no-arg构造函数编译类。

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 SummarySimple Comipler

You cannot. 你不能。 The .java file needs to be compiled into a .class so that you can use it. 需要将.java文件编译为.class,以便您可以使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM