View Javadoc

    1   /*
    2    $Id: MetaClassRegistry.java,v 1.17 2005/01/02 23:22:03 spullara Exp $
    3
    4    Copyright 2003 (C) James Strachan and Bob Mcwhirter. All Rights Reserved.
    5
    6    Redistribution and use of this software and associated documentation
    7    ("Software"), with or without modification, are permitted provided
    8    that the following conditions are met:
    9
    10   1. Redistributions of source code must retain copyright
    11      statements and notices.  Redistributions must also contain a
    12      copy of this document.
    13
    14   2. Redistributions in binary form must reproduce the
    15      above copyright notice, this list of conditions and the
    16      following disclaimer in the documentation and/or other
    17      materials provided with the distribution.
    18
    19   3. The name "groovy" must not be used to endorse or promote
    20      products derived from this Software without prior written
    21      permission of The Codehaus.  For written permission,
    22      please contact info@codehaus.org.
    23
    24   4. Products derived from this Software may not be called "groovy"
    25      nor may "groovy" appear in their names without prior written
    26      permission of The Codehaus. "groovy" is a registered
    27      trademark of The Codehaus.
    28
    29   5. Due credit should be given to The Codehaus -
    30      http://groovy.codehaus.org/
    31
    32   THIS SOFTWARE IS PROVIDED BY THE CODEHAUS AND CONTRIBUTORS
    33   ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
    34   NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
    35   FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
    36   THE CODEHAUS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
    37   INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    38   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    39   SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    40   HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
    41   STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    42   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
    43   OF THE POSSIBILITY OF SUCH DAMAGE.
    44
    45   */
    46  package groovy.lang;
    47
    48  import org.codehaus.groovy.runtime.DefaultGroovyMethods;
    49  import org.codehaus.groovy.runtime.DefaultGroovyStaticMethods;
    50
    51  import java.beans.IntrospectionException;
    52  import java.lang.reflect.Constructor;
    53  import java.security.AccessController;
    54  import java.security.PrivilegedAction;
    55  import java.util.*;
    56
    57  /***
    58   * A registery of MetaClass instances which caches introspection &
    59   * reflection information and allows methods to be dynamically added to
    60   * existing classes at runtime
    61   *
    62   * @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
    63   * @version $Revision: 1.17 $
    64   */
    65  public class MetaClassRegistry {
    66      private Map metaClasses = Collections.synchronizedMap(new HashMap());
    67      private boolean useAccessible;
    68      private GroovyClassLoader loader =
    69              (GroovyClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
    70                  public Object run() {
    71                      return new GroovyClassLoader(getClass().getClassLoader());
    72                  }
    73              });
    74
    75      public static final int LOAD_DEFAULT = 0;
    76      public static final int DONT_LOAD_DEFAULT = 1;
    77      private static MetaClassRegistry instanceInclude;
    78      private static MetaClassRegistry instanceExclude;
    79
    80
    81      public MetaClassRegistry() {
    82          this(true);
    83      }
    84
    85      public MetaClassRegistry(int loadDefault) {
    86          if (loadDefault == LOAD_DEFAULT) {
    87              this.useAccessible = true;
    88              // lets register the default methods
    89              lookup(DefaultGroovyMethods.class).registerInstanceMethods();
    90              lookup(DefaultGroovyStaticMethods.class).registerStaticMethods();
    91              checkInitialised();
    92          } else {
    93              this.useAccessible = true;
    94              // do nothing to avoid loading DefaultGroovyMethod
    95          }
    96      }
    97
    98      /***
    99       * @param useAccessible defines whether or not the {@link AccessibleObject.setAccessible()}
    100      *                      method will be called to enable access to all methods when using reflection
    101      */
    102     public MetaClassRegistry(boolean useAccessible) {
    103         this.useAccessible = useAccessible;
    104
    105         // lets register the default methods
    106         lookup(DefaultGroovyMethods.class).registerInstanceMethods();
    107         lookup(DefaultGroovyStaticMethods.class).registerStaticMethods();
    108         checkInitialised();
    109     }
    110
    111     public MetaClass getMetaClass(Class theClass) {
    112         synchronized(theClass) {
    113             MetaClass answer = (MetaClass) metaClasses.get(theClass);
    114             if (answer == null) {
    115                 try {
    116                     answer = new MetaClass(this, theClass);
    117                     answer.checkInitialised();
    118                 } catch (IntrospectionException e) {
    119                     throw new GroovyRuntimeException("Could not introspect class: " + theClass.getName() + ". Reason: " + e,
    120                             e);
    121                 }
    122                 metaClasses.put(theClass, answer);
    123             }
    124             return answer;
    125         }
    126     }
    127
    128     public void removeMetaClass(Class theClass) {
    129         metaClasses.remove(theClass);
    130     }
    131
    132
    133     /***
    134      * Registers a new MetaClass in the registry to customize the type
    135      *
    136      * @param theClass
    137      * @param theMetaClass
    138      */
    139     public void setMetaClass(Class theClass, MetaClass theMetaClass) {
    140         metaClasses.put(theClass, theMetaClass);
    141     }
    142
    143     public boolean useAccessible() {
    144         return useAccessible;
    145     }
    146
    147     /***
    148      * A helper class to load meta class bytecode into the class loader
    149      */
    150     public Class loadClass(final String name, final byte[] bytecode) throws ClassNotFoundException {
    151         return (Class) AccessController.doPrivileged(new PrivilegedAction() {
    152             public Object run() {
    153                 return loader.defineClass(name, bytecode, getClass().getProtectionDomain());
    154             }
    155         });
    156     }
    157
    158     public Class loadClass(String name) throws ClassNotFoundException {
    159         return loader.loadClass(name);
    160     }
    161
    162     /***
    163      * Ensures that all the registered MetaClass instances are initalized
    164      */
    165     void checkInitialised() {
    166         // lets copy all the classes in the repository right now
    167         // to avoid concurrent modification exception
    168         List list = new ArrayList(metaClasses.values());
    169         for (Iterator iter = list.iterator(); iter.hasNext();) {
    170             MetaClass metaClass = (MetaClass) iter.next();
    171             metaClass.checkInitialised();
    172         }
    173     }
    174
    175     /***
    176      * Used by MetaClass when registering new methods which avoids initializing the MetaClass instances on lookup
    177      */
    178     MetaClass lookup(Class theClass) {
    179         MetaClass answer = (MetaClass) metaClasses.get(theClass);
    180         if (answer == null) {
    181             try {
    182                 answer = new MetaClass(this, theClass);
    183             } catch (IntrospectionException e) {
    184                 throw new GroovyRuntimeException("Could not introspect class: " + theClass.getName() + ". Reason: " + e,
    185                         e);
    186             }
    187             metaClasses.put(theClass, answer);
    188         }
    189         return answer;
    190     }
    191
    192
    193     public MetaMethod getDefinedMethod(Class theClass, String methodName, Class[] args, boolean isStatic) {
    194         MetaClass metaclass = this.getMetaClass(theClass);
    195         if (metaclass == null) {
    196             return null;
    197         } else {
    198             if (isStatic) {
    199                 return metaclass.retrieveStaticMethod(methodName, args);
    200             } else {
    201                 return metaclass.retrieveMethod(methodName, args);
    202             }
    203         }
    204     }
    205
    206     public Constructor getDefinedConstructor(Class theClass, Class[] args) {
    207         MetaClass metaclass = this.getMetaClass(theClass);
    208         if (metaclass == null) {
    209             return null;
    210         } else {
    211             return metaclass.retrieveConstructor(args);
    212         }
    213     }
    214
    215     /***
    216      * Singleton of MetaClassRegistry. Shall we use threadlocal to store the instance?
    217      *
    218      * @param includeExtension
    219      * @return
    220      */
    221     public static MetaClassRegistry getIntance(int includeExtension) {
    222         if (includeExtension != DONT_LOAD_DEFAULT) {
    223             if (instanceInclude == null) {
    224                 instanceInclude = new MetaClassRegistry();
    225             }
    226             return instanceInclude;
    227         } else {
    228             if (instanceExclude == null) {
    229                 instanceExclude = new MetaClassRegistry(DONT_LOAD_DEFAULT);
    230             }
    231             return instanceExclude;
    232         }
    233     }
    234 }