Skip to main content
gamedev.net
🔒 Locked

[java] Is it possible to compile java source into executable bytecode at runtime

Started by Khaos Dragon Aug 8, 2007 at 10:35 AM 2 replies 1.2k views
Original Post
Khaos Dragon
Khaos Dragon
The title says it all. If possible, I would like to do something like the pseudocode below.

//Assume source is a class with one constructor that takes an array of strings
//as arguments. The array is preset in the calling program and passed to all 
//compiled source files

//In this case, compile from source would truncate the extension and return
//the string name. After completing, the class name.class should exist and be 
//be possible to invoke via reflection
String name = CompileFromSource( "name.java" );

Class.forName(name).getConstructors()[0].newInstance( (Object) args); 


OrangyTang
OrangyTang
IIRC, classes in com.sun.tools (like the javac used in that example) are non-standard and may vanish or change behaviour between VMs (ie. a newer vm could break your code).

I think there was a proper compiler API added in Java 6, you might want to look into that.
Stani R
Stani R
You can also use BeanShell to do this. It's a scripting language for Java and it supports Java syntax and generates Java bytecode. I'm not 100% sure how to get at the generated class though; it might be a bit more complicated than what your pseudocode has in mind.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.