// 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) 
import java.util.*;

import org.apache.bcel.*;
import org.apache.bcel.generic.*;

public class CodeGenAndLoad {
    private static Object get(Object o, String field) throws Exception {
        return o.getClass().getMethod("get" + field.substring(0, 1).toUpperCase() + field.substring(1), new Class[0]).invoke(o, new Object[0]);
    }
    private static void set(Object o, String field, int value) throws Exception {
        o.getClass().getMethod("set" + field.substring(0, 1).toUpperCase() + field.substring(1), new Class[] { int.class }).invoke(o, new Object[] { new Integer(value) });
    }
    private static void set(Object o, String field, double value) throws Exception {
        o.getClass().getMethod("set" + field.substring(0, 1).toUpperCase() + field.substring(1), new Class[] { double.class }).invoke(o, new Object[] { new Double(value) });
    }
    private static void set(Object o, String field, Object value) throws Exception {
        o.getClass().getMethod("set" + field.substring(0, 1).toUpperCase() + field.substring(1), new Class[] { value.getClass() }).invoke(o, new Object[] { value });
    }
    public static void main(String[] args) throws Exception {
        Map m = new HashMap();
        List d1 = new ArrayList();
        d1.add(new FieldDescrip("a", FieldDescrip.FIELD_INT));
        d1.add(new FieldDescrip("b", FieldDescrip.FIELD_DOUBLE));
        m.put("Bean1", d1);
        List d2 = new ArrayList();
        d2.add(new FieldDescrip("c", FieldDescrip.FIELD_INT));
        d2.add(new FieldDescrip("d", FieldDescrip.FIELD_STRING));
        m.put("Bean2", d2);
        SpecialClassLoader scl = new SpecialClassLoader(m);
        Class c1 = Class.forName("Bean1", true, scl);
        Object o1 = c1.newInstance();
        System.out.println(get(o1, "a"));
        System.out.println(get(o1, "b"));
        set(o1, "a", 123);
        set(o1, "b", 123.456);
        System.out.println(get(o1, "a"));
        System.out.println(get(o1, "b"));
        Class c2 = Class.forName("Bean2", true, scl);
        Object o2 = c2.newInstance();
        System.out.println(get(o2, "c"));
        System.out.println(get(o2, "d"));
        set(o2, "c", 123);
        set(o2, "d", "abc");
        System.out.println(get(o2, "c"));
        System.out.println(get(o2, "d"));
    }
}

class FieldDescrip {
    public final static int FIELD_INT = 1;
    public final static int FIELD_DOUBLE = 2;
    public final static int FIELD_STRING = 3;
    private String name;
    private int typ;
    public FieldDescrip(String name, int typ) {
        this.name = name;
        this.typ = typ;
    }
    public String getName() {
        return name;
    }
    public int getTyp() {
        return typ;
    }
}

class SpecialClassLoader extends ClassLoader {
    private Map m;
    public SpecialClassLoader(Map m) {
        this.m = m;
    }
    protected Class findClass(String name) {
        byte[] bc = generateClass(name);
        return defineClass(name, bc, 0, bc.length);
    }
    private Type typeToType(int typ) {
        switch(typ) {
            case FieldDescrip.FIELD_INT:
                return Type.INT;
            case FieldDescrip.FIELD_DOUBLE:
                return Type.DOUBLE;
            case FieldDescrip.FIELD_STRING:
                return Type.STRING;
            default:
                throw new RuntimeException("Bad field typ");
        }
    }
    private byte[] generateClass(String name) {
        ClassGen cg = new ClassGen(name, "java.lang.Object", "", Constants.ACC_PUBLIC | Constants.ACC_SUPER, new String[] { });
        ConstantPoolGen cpg = cg.getConstantPool();
        InstructionFactory ifact = new InstructionFactory(cg, cpg);
        List d = (List)m.get(name);
        for(int i = 0; i < d.size(); i++) {
            FieldDescrip fd = (FieldDescrip)d.get(i);
            FieldGen field = new FieldGen(Constants.ACC_PRIVATE, typeToType(fd.getTyp()), fd.getName(), cpg);
            cg.addField(field.getField());
        }
        InstructionList il = new InstructionList();
        MethodGen constructor = new MethodGen(Constants.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] {  }, "<init>", name, il, cpg);
        il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
        il.append(ifact.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL));
        il.append(InstructionFactory.createReturn(Type.VOID));
        constructor.setMaxStack();
        constructor.setMaxLocals();
        cg.addMethod(constructor.getMethod());
        il.dispose();
        for(int i = 0; i < d.size(); i++) {
            FieldDescrip fd = (FieldDescrip)d.get(i);
            MethodGen getter = new MethodGen(Constants.ACC_PUBLIC, typeToType(fd.getTyp()), Type.NO_ARGS, new String[] {  }, "get" + fd.getName().substring(0, 1).toUpperCase() + fd.getName().substring(1), name, il, cpg);
            il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
            il.append(ifact.createFieldAccess(name, fd.getName(), typeToType(fd.getTyp()), Constants.GETFIELD));
            il.append(InstructionFactory.createReturn(typeToType(fd.getTyp())));
            getter.setMaxStack();
            getter.setMaxLocals();
            cg.addMethod(getter.getMethod());
            il.dispose();
            MethodGen setter = new MethodGen(Constants.ACC_PUBLIC, Type.VOID, new Type[] { typeToType(fd.getTyp()) }, new String[] { "value" }, "set" + fd.getName().substring(0, 1).toUpperCase() + fd.getName().substring(1), name, il, cpg);
            il.append(InstructionFactory.createLoad(Type.OBJECT, 0));
            il.append(InstructionFactory.createLoad(typeToType(fd.getTyp()), 1));
            il.append(ifact.createFieldAccess(name, fd.getName(), typeToType(fd.getTyp()), Constants.PUTFIELD));
            il.append(InstructionFactory.createReturn(Type.VOID));
            setter.setMaxStack();
            setter.setMaxLocals();
            cg.addMethod(setter.getMethod());
            il.dispose();
        }
        return cg.getJavaClass().getBytes();
    }
}
