tags:

views:

76

answers:

3

Hi,

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

A: 

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

ivans
Isn't there a java library to compile java code into classes?
Paul Tomblin
That's not true, you can use the compiler directly from a java application..
Jack
@Jack that doesn't make his answer not true. All @ivans is saying is that the .java file has to be compiled first and that he can't magically get a class loaded from a .java file without compiling somehow.
whaley
That's true, you should point it out in a comment that what he is asking it's not clear, not as an answer :) I won't -1 anyway..
Jack
+6  A: 

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

Jack
A: 

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();
  }
}
Matthew Flaschen