Creating a Java object from an external java file

How to load a * .java class file into my java application and create an object based on this class file?

+3
source share
4 answers

You can do this using classes inside javax.tools. You will have a class ToolProviderfrom which you can get the compiler instance and compile the code at runtime. Later, you will upload files .classsimply compiled separately with ClassLoader, unless you get the binary directly for this class, and you can link it directly.

Look here

+7
source

Janino SimpleCompiler. , 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();
  }
}
+2

i think it helps: Package Summary Or Simple Compiler .

+1
source

You can not. The .java file needs to be compiled into .class so you can use it.

-1
source

Source: https://habr.com/ru/post/1747753/


All Articles