// 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.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class Mixerin {
    @SuppressWarnings("unchecked")
    public static <S,M> S createMixedin(final S source, final M mixedin) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(source.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                for(Method m : mixedin.getClass().getDeclaredMethods()) {
                    if(m.getName().equals(method.getName())) {
                        return m.invoke(mixedin, args);
                    }
                }
                return methodProxy.invoke(source, args);
            }
        });
        Class<?>[] args = source.getClass().getConstructors()[0].getParameterTypes();
        return (S)enhancer.create(args, new Object[args.length]);
    }
}
