// 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 java.util.Arrays;

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

public class Wrapper {
    @SuppressWarnings("unchecked")
    public static <S,W> W createWrapper(final S source, final Class<W> wrapperClass) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(wrapperClass);
        enhancer.setCallback(new MethodInterceptor() {
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                if (Arrays.asList(wrapperClass.getDeclaredMethods()).contains(method)) {
                    return methodProxy.invokeSuper(proxy, args);
                }
                return methodProxy.invoke(source, args);
            }
        });
        return (W)enhancer.create();
    }
}
