Reddy
Reddy

Reputation: 1628

Compile another java file from java file

Just out of curiosity. Can we compile & run a java file from another java program? If so, can you send a reference to that knowledge source?

Upvotes: 1

Views: 750

Answers (7)

Sajad Bahmani
Sajad Bahmani

Reputation: 17469

You can use javac (JDK is needed):
http://www.javaworld.com/javatips/jw-javatip131.html

Upvotes: 1

n0weak
n0weak

Reputation: 750

Take a look at Java Compiler Api and this little example.

Upvotes: 1

Miha
Miha

Reputation: 19

Yes, you can, but you need java compiler and not only java runtime. First you generate your source, save it and then use Dynamic class loading(tutorial http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html)

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 994531

If you're using Java 6, the best way to do this is through the javax.tools.JavaCompiler interface.

If you're using an older version of Java, you must call javac directly using Runtime.exec(), then load the class data by subclassing ClassLoader and overriding findClass.

Upvotes: 1

Thomas
Thomas

Reputation: 88757

Didn't read it thoroughly, but maybe this helps.

Upvotes: 1

Edwin Buck
Edwin Buck

Reputation: 70949

If you have the java source code already in a file, then you can just call the java compiler. The java compiler is built-in to the JVM libraries as of version 1.6.

The interface is documented here.

Upvotes: 1

Marcos Vasconcelos
Marcos Vasconcelos

Reputation: 18276

You can do it by calling the cmd prompt or use the Main class from the Java Code.

I don't know remember well how is it, but I did it a long time ago.

Upvotes: 0

Related Questions