// 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 ClassHack3 {
    public static void main(String[] args) throws NotFoundException, CannotCompileException {
        ClassPool pool = ClassPool.getDefault();
        CtClass cc = pool.get("hack.FooEntity");
        cc.addField(new CtField(pool.get("hack.Bar"), "b", cc));
        cc.addInterface(pool.get("hack.HasBar"));
        cc.addMethod(CtNewMethod.make("public hack.Bar getBar() { return b; }", cc));
        cc.addMethod(CtNewMethod.make("public void setBar(hack.Bar b) { this.b = b; }", cc));
        cc.getDeclaredMethod("getFooBar").setBody("if(b.isWhatever()) return \"fake\"; else return fooBar;");
        cc.toClass();
        FooEntity o = new FooEntity();
        o.setId(1L);
        o.setFooBar("ABC");
        ((HasBar)o).setBar(new Bar());
        System.out.println(o.getId() + " " + o.getFooBar() + " " + ((HasBar)o).getBar());
    }
}

