You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by si...@apache.org on 2012/01/22 15:15:06 UTC

svn commit: r1234514 - /commons/sandbox/beanutils2/trunk/src/main/java/org/apache/commons/beanutils2/AccessibleObjectsRegistry.java

Author: simonetripodi
Date: Sun Jan 22 14:15:05 2012
New Revision: 1234514

URL: http://svn.apache.org/viewvc?rev=1234514&view=rev
Log:
added methods registry implementation, codebase imported from current Beanutils' MethodUtils

Modified:
    commons/sandbox/beanutils2/trunk/src/main/java/org/apache/commons/beanutils2/AccessibleObjectsRegistry.java

Modified: commons/sandbox/beanutils2/trunk/src/main/java/org/apache/commons/beanutils2/AccessibleObjectsRegistry.java
URL: http://svn.apache.org/viewvc/commons/sandbox/beanutils2/trunk/src/main/java/org/apache/commons/beanutils2/AccessibleObjectsRegistry.java?rev=1234514&r1=1234513&r2=1234514&view=diff
==============================================================================
--- commons/sandbox/beanutils2/trunk/src/main/java/org/apache/commons/beanutils2/AccessibleObjectsRegistry.java (original)
+++ commons/sandbox/beanutils2/trunk/src/main/java/org/apache/commons/beanutils2/AccessibleObjectsRegistry.java Sun Jan 22 14:15:05 2012
@@ -20,12 +20,15 @@ package org.apache.commons.beanutils2;
 import static java.lang.System.getSecurityManager;
 import static java.lang.reflect.Modifier.isPublic;
 import static java.security.AccessController.doPrivileged;
-import static org.apache.commons.beanutils2.TypeUtils.isAssignmentCompatible;
+import static org.apache.commons.beanutils2.Assertions.checkArgument;
+import static org.apache.commons.beanutils2.TypeUtils.*;
 
 import java.lang.ref.Reference;
 import java.lang.ref.WeakReference;
 import java.lang.reflect.AccessibleObject;
 import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
 import java.security.PrivilegedAction;
 import java.util.Arrays;
 import java.util.Map;
@@ -39,11 +42,18 @@ abstract class AccessibleObjectsRegistry
 
     private static final AccessibleObjectsRegistry<Constructor<?>> CONSTRUCTORS_REGISTRY = new ConstructorsRegistry();
 
+    private static final AccessibleObjectsRegistry<Method> METHODS_REGISTRY = new MethodsRegistry();
+
     public static AccessibleObjectsRegistry<Constructor<?>> getConstructorsRegistry()
     {
         return CONSTRUCTORS_REGISTRY;
     }
 
+    public static AccessibleObjectsRegistry<Method> getMethodsRegistry()
+    {
+        return METHODS_REGISTRY;
+    }
+
     private final ReadWriteLock lock = new ReentrantReadWriteLock();
 
     private final Map<AccessibleObjectDescriptor, WeakReference<AO>> cache =
@@ -205,6 +215,297 @@ abstract class AccessibleObjectsRegistry
     }
 
     /**
+     * Methods registry
+     */
+    private static final class MethodsRegistry extends AccessibleObjectsRegistry<Method>
+    {
+
+        @Override
+        public Method resolve( boolean exact, Class<?> clazz, String methodName, Class<?>...parameterTypes )
+        {
+            // see if we can find the method directly
+            // most of the time this works and it's much faster
+            try
+            {
+                Method method = clazz.getMethod(methodName, parameterTypes);
+                if ( exact || method != null )
+                {
+                    return method;
+                }
+            }
+            catch ( NoSuchMethodException e )
+            {
+                /* SWALLOW */
+                if ( exact )
+                {
+                    return null;
+                }
+            }
+
+            // search through all methods
+            int paramSize = parameterTypes.length;
+            Method bestMatch = null;
+            Method[] methods = clazz.getMethods();
+            float bestMatchCost = Float.MAX_VALUE;
+            float myCost = Float.MAX_VALUE;
+            for ( int i = 0, size = methods.length; i < size; i++ )
+            {
+                if ( methods[i].getName().equals( methodName ) )
+                {
+                    // compare parameters
+                    Class<?>[] methodsParams = methods[i].getParameterTypes();
+                    int methodParamSize = methodsParams.length;
+                    if ( methodParamSize == paramSize )
+                    {
+                        boolean match = true;
+                        for ( int n = 0; n < methodParamSize; n++ )
+                        {
+
+                            if ( !isAssignmentCompatible( methodsParams[n], parameterTypes[n] ) )
+                            {
+                                match = false;
+                                break;
+                            }
+                        }
+
+                        if ( match )
+                        {
+                            // get accessible version of method
+                            Method method = getAccessibleMethod( clazz, methods[i] );
+                            if ( method != null )
+                            {
+                                myCost = getTotalTransformationCost( parameterTypes, method.getParameterTypes() );
+                                if ( myCost < bestMatchCost )
+                                {
+                                    bestMatch = method;
+                                    bestMatchCost = myCost;
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+
+            return bestMatch;
+        }
+
+        /**
+         * <p>Return an accessible method (that is, one that can be invoked via
+         * reflection) that implements the specified Method.  If no such method
+         * can be found, return <code>null</code>.</p>
+         *
+         * @param clazz The class of the object
+         * @param method The method that we wish to call
+         * @return The accessible method
+         */
+        private static Method getAccessibleMethod(Class<?> clazz, Method method) {
+            // Make sure we have a method to check
+            if ( method == null )
+            {
+                return ( null );
+            }
+
+            // If the requested method is not public we cannot call it
+            if ( !Modifier.isPublic( method.getModifiers() ) )
+            {
+                return ( null );
+            }
+
+            if ( clazz == null )
+            {
+                clazz = method.getDeclaringClass();
+            }
+            else
+            {
+                checkArgument( method.getDeclaringClass().isAssignableFrom( clazz ),
+                               "%s is not assignable from ", clazz.getName(), method.getDeclaringClass().getName() );
+            }
+
+            // If the class is public, we are done
+            if ( isPublic( clazz.getModifiers() ) )
+            {
+                return method;
+            }
+
+            String methodName = method.getName();
+            Class<?>[] parameterTypes = method.getParameterTypes();
+
+            // Check the implemented interfaces and subinterfaces
+            method = getAccessibleMethodFromInterfaceNest( clazz, methodName, parameterTypes );
+
+            // Check the superclass chain
+            if ( method == null )
+            {
+                method = getAccessibleMethodFromSuperclass( clazz, methodName, parameterTypes );
+            }
+
+            return method;
+        }
+
+        /**
+         * Returns the sum of the object transformation cost for each class in the source
+         * argument list.
+         * @param srcArgs The source arguments
+         * @param destArgs The destination arguments
+         * @return The total transformation cost
+         */
+        private static float getTotalTransformationCost( Class<?>[] srcArgs, Class<?>[] destArgs )
+        {
+            float totalCost = 0.0f;
+            for ( int i = 0; i < srcArgs.length; i++ )
+            {
+                Class<?> srcClass, destClass;
+                srcClass = srcArgs[i];
+                destClass = destArgs[i];
+                totalCost += getObjectTransformationCost( srcClass, destClass );
+            }
+            return totalCost;
+        }
+
+        /**
+         * Gets the number of steps required needed to turn the source class into the
+         * destination class. This represents the number of steps in the object hierarchy
+         * graph.
+         *
+         * @param srcClass The source class
+         * @param destClass The destination class
+         * @return The cost of transforming an object
+         */
+        private static float getObjectTransformationCost( Class<?> srcClass, Class<?> destClass )
+        {
+            float cost = 0.0f;
+            while ( srcClass != null && !destClass.equals( srcClass ) )
+            {
+                if ( destClass.isPrimitive() )
+                {
+                    Class<?> destClassWrapperClazz = getPrimitiveWrapper( destClass );
+                    if ( destClassWrapperClazz != null && destClassWrapperClazz.equals( srcClass ) )
+                    {
+                        cost += 0.25f;
+                        break;
+                    }
+                }
+                if ( destClass.isInterface() && isAssignmentCompatible( destClass, srcClass ) )
+                {
+                    // slight penalty for interface match.
+                    // we still want an exact match to override an interface match, but
+                    // an interface match should override anything where we have to get a
+                    // superclass.
+                    cost += 0.25f;
+                    break;
+                }
+                cost++;
+                srcClass = srcClass.getSuperclass();
+            }
+
+            /*
+             * If the destination class is null, we've travelled all the way up to an Object match. We'll penalize this
+             * by adding 1.5 to the cost.
+             */
+            if ( srcClass == null )
+            {
+                cost += 1.5f;
+            }
+
+            return cost;
+        }
+
+        /**
+         * <p>Return an accessible method (that is, one that can be invoked via
+         * reflection) by scanning through the superclasses. If no such method
+         * can be found, return <code>null</code>.</p>
+         *
+         * @param clazz Class to be checked
+         * @param methodName Method name of the method we wish to call
+         * @param parameterTypes The parameter type signatures
+         */
+        private static Method getAccessibleMethodFromSuperclass( Class<?> clazz, String methodName,
+                                                                 Class<?>... parameterTypes )
+        {
+            Class<?> parentClazz = clazz.getSuperclass();
+            while ( parentClazz != null )
+            {
+                if ( isPublic( parentClazz.getModifiers() ) )
+                {
+                    try
+                    {
+                        return parentClazz.getMethod( methodName, parameterTypes );
+                    }
+                    catch ( NoSuchMethodException e )
+                    {
+                        // go ahead until found or parentClazz == null
+                    }
+                }
+                parentClazz = parentClazz.getSuperclass();
+            }
+            return null;
+        }
+
+        /**
+         * <p>Return an accessible method (that is, one that can be invoked via
+         * reflection) that implements the specified method, by scanning through
+         * all implemented interfaces and subinterfaces.  If no such method
+         * can be found, return <code>null</code>.</p>
+         *
+         * <p> There isn't any good reason why this method must be private.
+         * It is because there doesn't seem any reason why other classes should
+         * call this rather than the higher level methods.</p>
+         *
+         * @param clazz Parent class for the interfaces to be checked
+         * @param methodName Method name of the method we wish to call
+         * @param parameterTypes The parameter type signatures
+         */
+        private static Method getAccessibleMethodFromInterfaceNest( Class<?> clazz, String methodName,
+                                                                    Class<?>... parameterTypes )
+        {
+            Method method = null;
+
+            // Search up the superclass chain
+            while ( clazz != null )
+            {
+                // Check the implemented interfaces of the parent class
+                for ( Class<?> interfaceType : clazz.getInterfaces() )
+                {
+                    // Is this interface public?
+                    if ( !isPublic( interfaceType.getModifiers() ) )
+                    {
+                        continue;
+                    }
+
+                    // Does the method exist on this interface?
+                    try
+                    {
+                        method = interfaceType.getDeclaredMethod( methodName, parameterTypes );
+                    }
+                    catch ( NoSuchMethodException e )
+                    {
+                        /*
+                         * Swallow, if no method is found after the loop then this method returns null.
+                         */
+                    }
+                    if ( method != null )
+                    {
+                        return method;
+                    }
+
+                    // Recursively check our parent interfaces
+                    method = getAccessibleMethodFromInterfaceNest( interfaceType, methodName, parameterTypes );
+                    if ( method != null )
+                    {
+                        return method;
+                    }
+                }
+
+                clazz = clazz.getSuperclass();
+            }
+
+            // We did not find anything
+            return null;
+        }
+
+    }
+
+    /**
      * Represents the key to looking up an AccessibleObject by reflection.
      */
     private static final class AccessibleObjectDescriptor