001package ch.qos.logback.core.joran.util.beans;
002
003import java.util.HashMap;
004import java.util.Map;
005
006import ch.qos.logback.core.Context;
007import ch.qos.logback.core.spi.ContextAwareBase;
008
009/**
010 *
011 * Cache for {@link BeanDescription} instances. All the cache users which use
012 * the same instance of BeanDescriptionCache can profit from each others cached
013 * bean descriptions.
014 * 
015 * <p>
016 * The cache is not thread-safe and should not be shared across configurator
017 * instances.
018 *
019 * @author urechm
020 *
021 */
022public class BeanDescriptionCache extends ContextAwareBase {
023
024    private Map<Class<?>, BeanDescription> classToBeanDescription = new HashMap<Class<?>, BeanDescription>();
025    private BeanDescriptionFactory beanDescriptionFactory;
026
027    public BeanDescriptionCache(Context context) {
028        setContext(context);
029    }
030
031    private BeanDescriptionFactory getBeanDescriptionFactory() {
032        if (beanDescriptionFactory == null) {
033            beanDescriptionFactory = new BeanDescriptionFactory(getContext());
034        }
035        return beanDescriptionFactory;
036    }
037
038    /**
039     * Returned bean descriptions are hold in a cache. If the cache does not contain
040     * a description for a given class, a new bean description is created and put in
041     * the cache, before it is returned.
042     *
043     * @param clazz to get a bean description for.
044     * @return a bean description for the given class.
045     */
046    public BeanDescription getBeanDescription(Class<?> clazz) {
047        if (!classToBeanDescription.containsKey(clazz)) {
048            BeanDescription beanDescription = getBeanDescriptionFactory().create(clazz);
049            classToBeanDescription.put(clazz, beanDescription);
050        }
051        return classToBeanDescription.get(clazz);
052    }
053
054}