/************************************************
 * Copyright (c) Shen Li. All rights reserved.  *
 * http://joyaop.sourceforge.net                *
 * -------------------------------------------- *
 * Distributable under LGPL license.            *
 * See terms of license at gnu.org.             *
 ************************************************/
package net.sf.joyaop.extension.picocontainer;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;

import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Shen Li
 */
public abstract class AbstractClassUtils {
    private static final Map wrappers = new HashMap();

    public static Class wrap(Class clazz) {
        if (Modifier.isAbstract(clazz.getModifiers())) {
            synchronized (wrappers) {
                Class wrapper = (Class) wrappers.get(clazz);
                if (wrapper == null) {
                    Enhancer enhancer = new Enhancer();
                    enhancer.setSuperclass(clazz);
                    enhancer.setCallbackType(NoOp.class);
                    enhancer.setInterfaces(new Class[] { Wrapper.class });
                    wrapper = enhancer.createClass();
                    wrappers.put(clazz, wrapper);
                }
                return wrapper;
            }
        }
        return clazz;
    }

    public static Class unwrap(Class clazz) {
        if (Wrapper.class.isAssignableFrom(clazz)) {
            return clazz.getSuperclass();
        }
        return clazz;
    }
}
