// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
package hack;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.CtNewMethod;
import javassist.NotFoundException;

public class ClassHack2 {
    public static void main(String[] args) throws NotFoundException, CannotCompileException {
        ClassPool pool = ClassPool.getDefault();
        CtClass cc = pool.get("hack.FooEntity");
        cc.addField(new CtField(CtClass.doubleType, "x", cc));
        cc.addInterface(pool.get("hack.FooHack"));
        cc.addMethod(CtNewMethod.make("public void print() { System.out.println(id + \" \" + fooBar + \" \" + x); }", cc));
        cc.getDeclaredMethod("setFooBar").insertBefore("x += 123.456;");
        cc.toClass();
        FooEntity o = new FooEntity();
        o.setId(1L);
        o.setFooBar("ABC");
        o.setFooBar("DEF");
        FooHack o2 = (FooHack)o;
        o2.print();
    }
}

