001/*
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v2.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014
015package ch.qos.logback.core.joran.util.beans;
016
017import java.util.HashMap;
018import java.util.Map;
019
020import ch.qos.logback.core.Context;
021import ch.qos.logback.core.spi.ContextAwareBase;
022
023/**
024 *
025 * Cache for {@link BeanDescription} instances. All the cache users which use
026 * the same instance of BeanDescriptionCache can profit from each others cached
027 * bean descriptions.
028 * 
029 * <p>
030 * The cache is not thread-safe and should not be shared across configurator
031 * instances.
032 *
033 * @author urechm
034 *
035 */
036public class BeanDescriptionCache extends ContextAwareBase {
037
038    private Map<Class<?>, BeanDescription> classToBeanDescription = new HashMap<Class<?>, BeanDescription>();
039    private BeanDescriptionFactory beanDescriptionFactory;
040
041    public BeanDescriptionCache(Context context) {
042        setContext(context);
043    }
044
045    private BeanDescriptionFactory getBeanDescriptionFactory() {
046        if (beanDescriptionFactory == null) {
047            beanDescriptionFactory = new BeanDescriptionFactory(getContext());
048        }
049        return beanDescriptionFactory;
050    }
051
052    /**
053     * Returned bean descriptions are hold in a cache. If the cache does not contain
054     * a description for a given class, a new bean description is created and put in
055     * the cache, before it is returned.
056     *
057     * @param clazz to get a bean description for.
058     * @return a bean description for the given class.
059     */
060    public BeanDescription getBeanDescription(Class<?> clazz) {
061        if (!classToBeanDescription.containsKey(clazz)) {
062            BeanDescription beanDescription = getBeanDescriptionFactory().create(clazz);
063            classToBeanDescription.put(clazz, beanDescription);
064        }
065        return classToBeanDescription.get(clazz);
066    }
067
068}