Skip to content

Instantly share code, notes, and snippets.

@edefazio
Last active January 8, 2017 19:59
Show Gist options
  • Save edefazio/fd9b456470307cd7633f98238eff350e to your computer and use it in GitHub Desktop.
Save edefazio/fd9b456470307cd7633f98238eff350e to your computer and use it in GitHub Desktop.
How to load and change existing .java source code at runtime
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"
}
}
@edefazio
Copy link
Author

edefazio commented Nov 30, 2016

will print
"Tailor"
...to the console, and will write out the following .java source file to {java.temp.dir}\Tailored.java

public class Tailored
{
    public int count;
    private final String message;
    public Tailored( String message )
    {
        this.message = message;
    }

    public final String toString(  )
    {
        return this.message;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment