Last active
January 8, 2017 19:59
-
-
Save edefazio/fd9b456470307cd7633f98238eff350e to your computer and use it in GitHub Desktop.
How to load and change existing .java source code at runtime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package quickstart.java; | |
import varcode.java.adhoc.Export; | |
import varcode.java.meta._Java; | |
import varcode.java.meta._class; | |
public class TailorExistingCode | |
{ | |
public class Existing { | |
public int count; | |
public Existing() { | |
} | |
} | |
public static void main( String[] args ) | |
{ | |
/* load the _class model from the Existing java nested class */ | |
_class _c = _Java.Nested._classFrom( Existing.class ); | |
/* change the _class */ | |
_c.setName( "Tailored" ); //rename from "Existing" to "Tailored" | |
_c.field( "private final String message;"); //add a new field | |
_c.getConstructors().getAt( 0 ) //add a param to the constructor | |
.addParameter( "String", "message" ) | |
.setBody( "this.message = message;" ); //modify ctor body | |
_c.method( "public final String toString()", //add a toString method | |
"return this.message;" ); | |
Export.TEMP_DIR.file( _c ); //write the .java code to the temp dir | |
/* compile, load and create a new "ad hoc" instance of the class */ | |
Object adHocInstance = _c.instance( "Tailor" ); //new Tailored("Tailor") | |
System.out.println( adHocInstance ); //prints "Tailor" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
will print
"Tailor"
...to the console, and will write out the following .java source file to {java.temp.dir}\Tailored.java