⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 classmap.java

📁 velocity 的脚本语言的全部代码集合
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package org.apache.velocity.util.introspection;

/*
 * Copyright 2001,2004 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.Map;
import java.util.List;
import java.util.Hashtable;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * A cache of introspection information for a specific class instance.
 * Keys {@link java.lang.Method} objects by a concatenation of the
 * method name and the names of classes that make up the parameters.
 *
 * @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a>
 * @author <a href="mailto:bob@werken.com">Bob McWhirter</a>
 * @author <a href="mailto:szegedia@freemail.hu">Attila Szegedi</a>
 * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
 * @version $Id: ClassMap.java,v 1.20.8.1 2004/03/03 23:23:08 geirm Exp $
 */
public class ClassMap
{
    private static final class CacheMiss { }
    private static final CacheMiss CACHE_MISS = new CacheMiss();
    private static final Object OBJECT = new Object();

    /** 
     * Class passed into the constructor used to as
     * the basis for the Method map.
     */

    private Class clazz;

    /**
     * Cache of Methods, or CACHE_MISS, keyed by method
     * name and actual arguments used to find it.
     */
    private Map methodCache = new Hashtable();

    private MethodMap methodMap = new MethodMap();

    /**
     * Standard constructor
     */
    public ClassMap( Class clazz)
    {
        this.clazz = clazz;
        populateMethodCache();
    }

    private ClassMap()
    {
    }

    /**
     * @return the class object whose methods are cached by this map.
     */
     Class getCachedClass()
     {
         return clazz;
     }
    
    /**
     * Find a Method using the methodKey
     * provided.
     *
     * Look in the methodMap for an entry.  If found,
     * it'll either be a CACHE_MISS, in which case we
     * simply give up, or it'll be a Method, in which
     * case, we return it.
     *
     * If nothing is found, then we must actually go
     * and introspect the method from the MethodMap.
     */
    public Method findMethod(String name, Object[] params)
        throws MethodMap.AmbiguousException
    {
        String methodKey = makeMethodKey(name, params);
        Object cacheEntry = methodCache.get( methodKey );

        if (cacheEntry == CACHE_MISS)
        {
            return null;
        }

        if (cacheEntry == null)
        {
            try
            {
                cacheEntry = methodMap.find( name,
                                             params );
            }
            catch( MethodMap.AmbiguousException ae )
            {
                /*
                 *  that's a miss :)
                 */

                methodCache.put( methodKey,
                                 CACHE_MISS );

                throw ae;
            }

            if ( cacheEntry == null )
            {
                methodCache.put( methodKey,
                                 CACHE_MISS );
            }
            else
            {
                methodCache.put( methodKey,
                                 cacheEntry );
            }
        }

        // Yes, this might just be null.
        
        return (Method) cacheEntry;
    }
    
    /**
     * Populate the Map of direct hits. These
     * are taken from all the public methods
     * that our class provides.
     */
    private void populateMethodCache()
    {
        StringBuffer methodKey;

        /*
         *  get all publicly accessible methods
         */

        Method[] methods = getAccessibleMethods(clazz);

        /*
         * map and cache them
         */

        for (int i = 0; i < methods.length; i++)
        {
            Method method = methods[i];

            /*
             *  now get the 'public method', the method declared by a 
             *  public interface or class. (because the actual implementing
             *  class may be a facade...
             */

            Method publicMethod = getPublicMethod( method );

            /*
             *  it is entirely possible that there is no public method for
             *  the methods of this class (i.e. in the facade, a method
             *  that isn't on any of the interfaces or superclass
             *  in which case, ignore it.  Otherwise, map and cache
             */

            if ( publicMethod != null)
            {
                methodMap.add( publicMethod );
                methodCache.put(  makeMethodKey( publicMethod), publicMethod);
            }
        }            
    }

    /**
     * Make a methodKey for the given method using
     * the concatenation of the name and the
     * types of the method parameters.
     */
    private String makeMethodKey(Method method)
    {
        Class[] parameterTypes = method.getParameterTypes();
        
        StringBuffer methodKey = new StringBuffer(method.getName());
        
        for (int j = 0; j < parameterTypes.length; j++)
        {
            /*
             * If the argument type is primitive then we want
             * to convert our primitive type signature to the 
             * corresponding Object type so introspection for
             * methods with primitive types will work correctly.
             */
            if (parameterTypes[j].isPrimitive())
            {
                if (parameterTypes[j].equals(Boolean.TYPE))
                    methodKey.append("java.lang.Boolean");
                else if (parameterTypes[j].equals(Byte.TYPE))
                    methodKey.append("java.lang.Byte");
                else if (parameterTypes[j].equals(Character.TYPE))
                    methodKey.append("java.lang.Character");
                else if (parameterTypes[j].equals(Double.TYPE))
                    methodKey.append("java.lang.Double");
                else if (parameterTypes[j].equals(Float.TYPE))
                    methodKey.append("java.lang.Float");
                else if (parameterTypes[j].equals(Integer.TYPE))
                    methodKey.append("java.lang.Integer");
                else if (parameterTypes[j].equals(Long.TYPE))
                    methodKey.append("java.lang.Long");
                else if (parameterTypes[j].equals(Short.TYPE))
                    methodKey.append("java.lang.Short");
            }                
            else
            {
                methodKey.append(parameterTypes[j].getName());
            }
        }            
        
        return methodKey.toString();
    }

    private static String makeMethodKey(String method, Object[] params)
    {
        StringBuffer methodKey = new StringBuffer().append(method);

        for (int j = 0; j < params.length; j++)
        {
            Object arg = params[j];

            if (arg == null)
            {
                arg = OBJECT;
            }

            methodKey.append(arg.getClass().getName());
        }
        
        return methodKey.toString();
    }

    /**
     * Retrieves public methods for a class. In case the class is not
     * public, retrieves methods with same signature as its public methods
     * from public superclasses and interfaces (if they exist). Basically
     * upcasts every method to the nearest acccessible method.
     */
    private static Method[] getAccessibleMethods(Class clazz)
    {
        Method[] methods = clazz.getMethods();
        
        /*
         *  Short circuit for the (hopefully) majority of cases where the
         *  clazz is public

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -