Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Java object from external java file

Tags:

java

object

How can I load a *.java class file into my java app and create an object based on that class file?

like image 954
psu Avatar asked Jan 28 '26 08:01

psu


2 Answers

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

like image 101
Jack Avatar answered Jan 30 '26 23:01

Jack


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();
  }
}
like image 40
Matthew Flaschen Avatar answered Jan 31 '26 00:01

Matthew Flaschen