View Javadoc

    1   /*
    2    * Copyright 2004-2009 the Seasar Foundation and the Others.
    3    *
    4    * Licensed under the Apache License, Version 2.0 (the "License");
    5    * you may not use this file except in compliance with the License.
    6    * You may obtain a copy of the License at
    7    *
    8    *     http://www.apache.org/licenses/LICENSE-2.0
    9    *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
    13   * either express or implied. See the License for the specific language
    14   * governing permissions and limitations under the License.
    15   */
    16  package org.seasar.cubby.spi.impl;
    17
    18  import java.util.HashMap;
    19  import java.util.Map;
    20
    21  import org.seasar.cubby.converter.Converter;
    22
    23  /**
    24   * コンバータのキャッシュを備えたコンバータプロバイダのスケルトン実装です。
    25   *
    26   * @author baba
    27   */
    28  public abstract class AbstractCachedConverterProvider extends
    29  		AbstractConverterProvider {
    30
    31  	/** コンバータのキャッシュです。 */
    32  	private final Map<String, Converter> converterCache = new HashMap<String, Converter>();
    33
    34  	/**
    35  	 * {@inheritDoc}
    36  	 */
    37  	@Override
    38  	public Converter getConverter(final Class<?> parameterType,
    39  			final Class<?> objectType) {
    40  		final Class<?> destType = ConversionUtils
    41  				.getWrapperClassIfPrimitive(objectType);
    42  		final String cacheKey = cacheKey(parameterType, destType);
    43  		final Converter converter = converterCache.get(cacheKey);
    44  		if (converter != null) {
    45  			return converter;
    46  		}
    47  		return detectConverter(parameterType, destType);
    48  	}
    49
    50  	private Converter detectConverter(final Class<?> parameterType,
    51  			final Class<?> objectType) {
    52  		final Converter converter = super.getConverter(parameterType,
    53  				objectType);
    54  		final String cacheKey = cacheKey(parameterType, objectType);
    55  		converterCache.put(cacheKey, converter);
    56  		return converter;
    57  	}
    58
    59  	private static String cacheKey(final Class<?> parameterType,
    60  			final Class<?> objectType) {
    61  		if (parameterType == null) {
    62  			return objectType.getName();
    63  		}
    64  		return parameterType.getName() + objectType.getName();
    65  	}
    66
    67  	/**
    68  	 * キャッシュをクリアします。
    69  	 */
    70  	protected void clear() {
    71  		this.converterCache.clear();
    72  	}
    73
    74  }