001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.camel.component.bean;
018
019 import java.lang.reflect.Method;
020 import java.util.Map;
021
022 import org.apache.camel.CamelContext;
023 import org.apache.camel.util.LRUCache;
024
025 /**
026 * Represents a cache of MethodInfo objects to avoid the expense of introspection for each invocation of a method
027 * via a proxy
028 *
029 * @version $Revision: 747062 $
030 */
031 public class MethodInfoCache {
032 private final CamelContext camelContext;
033 private Map<Method, MethodInfo> methodCache;
034 private Map<Class, BeanInfo> classCache;
035
036 public MethodInfoCache(CamelContext camelContext) {
037 this(camelContext, 1000, 10000);
038 }
039
040 @SuppressWarnings("unchecked")
041 public MethodInfoCache(CamelContext camelContext, int classCacheSize, int methodCacheSize) {
042 this(camelContext, createLruCache(classCacheSize), createLruCache(methodCacheSize));
043 }
044
045 public MethodInfoCache(CamelContext camelContext, Map<Class, BeanInfo> classCache, Map<Method, MethodInfo> methodCache) {
046 this.camelContext = camelContext;
047 this.classCache = classCache;
048 this.methodCache = methodCache;
049 }
050
051 public synchronized MethodInfo getMethodInfo(Method method) {
052 MethodInfo answer = methodCache.get(method);
053 if (answer == null) {
054 answer = createMethodInfo(method);
055 methodCache.put(method, answer);
056 }
057 return answer;
058 }
059
060 protected MethodInfo createMethodInfo(Method method) {
061 Class<?> declaringClass = method.getDeclaringClass();
062 BeanInfo info = getBeanInfo(declaringClass);
063 return info.getMethodInfo(method);
064 }
065
066 protected synchronized BeanInfo getBeanInfo(Class<?> declaringClass) {
067 BeanInfo beanInfo = classCache.get(declaringClass);
068 if (beanInfo == null) {
069 beanInfo = createBeanInfo(declaringClass);
070 classCache.put(declaringClass, beanInfo);
071 }
072 return beanInfo;
073 }
074
075 protected BeanInfo createBeanInfo(Class<?> declaringClass) {
076 return new BeanInfo(camelContext, declaringClass);
077 }
078
079 protected static Map createLruCache(int size) {
080 return new LRUCache(size);
081 }
082 }