// 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 ap;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

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

public class FooTransformer implements ClassFileTransformer {
	public byte[] transform(ClassLoader loader,
			                String className,
			                Class<?> classBeingRedefined,
			                ProtectionDomain protectionDomain,
			                byte[] classfileBuffer) throws IllegalClassFormatException {
        try {
            ClassPool pool = ClassPool.getDefault();
            CtClass cc = pool.makeClass(new ByteArrayInputStream(classfileBuffer));
            if(cc.getInterfaces().length >= 1 && cc.getInterfaces()[0].getName().equals("apd.Foo")) {
                cc.addMethod(CtNewMethod.make("public String toString() { return \"agents are fun\"; }", cc));
                return cc.toBytecode();
            } else {
                return classfileBuffer;
            }
        } catch (IOException | RuntimeException | CannotCompileException | NotFoundException e) {
            e.printStackTrace();
            return null;
        }
	}
}
