001 /* 002 $Id: MetaClassRegistry.java,v 1.26 2005/10/21 09:03:03 tug Exp $ 003 004 Copyright 2003 (C) James Strachan and Bob Mcwhirter. All Rights Reserved. 005 006 Redistribution and use of this software and associated documentation 007 ("Software"), with or without modification, are permitted provided 008 that the following conditions are met: 009 010 1. Redistributions of source code must retain copyright 011 statements and notices. Redistributions must also contain a 012 copy of this document. 013 014 2. Redistributions in binary form must reproduce the 015 above copyright notice, this list of conditions and the 016 following disclaimer in the documentation and/or other 017 materials provided with the distribution. 018 019 3. The name "groovy" must not be used to endorse or promote 020 products derived from this Software without prior written 021 permission of The Codehaus. For written permission, 022 please contact info@codehaus.org. 023 024 4. Products derived from this Software may not be called "groovy" 025 nor may "groovy" appear in their names without prior written 026 permission of The Codehaus. "groovy" is a registered 027 trademark of The Codehaus. 028 029 5. Due credit should be given to The Codehaus - 030 http://groovy.codehaus.org/ 031 032 THIS SOFTWARE IS PROVIDED BY THE CODEHAUS AND CONTRIBUTORS 033 ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT 034 NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 035 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 036 THE CODEHAUS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 037 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 038 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 039 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 040 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 041 STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 042 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 043 OF THE POSSIBILITY OF SUCH DAMAGE. 044 045 */ 046 package groovy.lang; 047 048 import java.beans.IntrospectionException; 049 import java.lang.reflect.Constructor; 050 import java.lang.reflect.Method; 051 import java.security.AccessController; 052 import java.security.PrivilegedAction; 053 import java.util.ArrayList; 054 import java.util.Collections; 055 import java.util.Iterator; 056 import java.util.List; 057 import java.util.Map; 058 import java.util.WeakHashMap; 059 060 import org.codehaus.groovy.runtime.DefaultGroovyMethods; 061 import org.codehaus.groovy.runtime.DefaultGroovyStaticMethods; 062 import org.codehaus.groovy.runtime.MethodHelper; 063 064 /** 065 * A registery of MetaClass instances which caches introspection & 066 * reflection information and allows methods to be dynamically added to 067 * existing classes at runtime 068 * 069 * @author <a href="mailto:james@coredevelopers.net">James Strachan</a> 070 * @version $Revision: 1.26 $ 071 */ 072 /** 073 * @author John Wilson 074 * 075 */ 076 public class MetaClassRegistry { 077 private Map metaClasses = Collections.synchronizedMap(new WeakHashMap()); 078 private boolean useAccessible; 079 private Map loaderMap = Collections.synchronizedMap(new WeakHashMap()); 080 private GroovyClassLoader loader = 081 (GroovyClassLoader) AccessController.doPrivileged(new PrivilegedAction() { 082 public Object run() { 083 return new GroovyClassLoader(getClass().getClassLoader()); 084 } 085 }); 086 087 public static final int LOAD_DEFAULT = 0; 088 public static final int DONT_LOAD_DEFAULT = 1; 089 private static MetaClassRegistry instanceInclude; 090 private static MetaClassRegistry instanceExclude; 091 092 093 public MetaClassRegistry() { 094 this(LOAD_DEFAULT, true); 095 } 096 097 public MetaClassRegistry(int loadDefault) { 098 this(loadDefault, true); 099 } 100 101 /** 102 * @param useAccessible defines whether or not the {@link java.lang.reflect.AccessibleObject.setAccessible();} 103 * method will be called to enable access to all methods when using reflection 104 */ 105 public MetaClassRegistry(boolean useAccessible) { 106 this(LOAD_DEFAULT, useAccessible); 107 } 108 109 public MetaClassRegistry(final int loadDefault, final boolean useAccessible) { 110 this.useAccessible = useAccessible; 111 112 if (loadDefault == LOAD_DEFAULT) { 113 // lets register the default methods 114 lookup(DefaultGroovyMethods.class); 115 registerMethods(DefaultGroovyMethods.class, true); 116 lookup(DefaultGroovyStaticMethods.class); 117 registerMethods(DefaultGroovyStaticMethods.class, false); 118 checkInitialised(); 119 } 120 } 121 122 private void registerMethods(final Class theClass, final boolean instanceMethods) { 123 Method[] methods = theClass.getMethods(); 124 for (int i = 0; i < methods.length; i++) { 125 Method method = methods[i]; 126 if (MethodHelper.isStatic(method)) { 127 Class[] paramTypes = method.getParameterTypes(); 128 if (paramTypes.length > 0) { 129 Class owner = paramTypes[0]; 130 if (instanceMethods) { 131 lookup(owner).addNewInstanceMethod(method); 132 } else { 133 lookup(owner).addNewStaticMethod(method); 134 } 135 } 136 } 137 } 138 } 139 140 public MetaClass getMetaClass(Class theClass) { 141 synchronized (theClass) { 142 MetaClass answer = (MetaClass) metaClasses.get(theClass); 143 if (answer == null) { 144 answer = getMetaClassFor(theClass); 145 answer.checkInitialised(); 146 metaClasses.put(theClass, answer); 147 } 148 return answer; 149 } 150 } 151 152 public void removeMetaClass(Class theClass) { 153 metaClasses.remove(theClass); 154 } 155 156 157 /** 158 * Registers a new MetaClass in the registry to customize the type 159 * 160 * @param theClass 161 * @param theMetaClass 162 */ 163 public void setMetaClass(Class theClass, MetaClass theMetaClass) { 164 metaClasses.put(theClass, theMetaClass); 165 } 166 167 public boolean useAccessible() { 168 return useAccessible; 169 } 170 171 /** 172 * A helper class to load meta class bytecode into the class loader 173 */ 174 public Class loadClass(final String name, final byte[] bytecode) throws ClassNotFoundException { 175 return (Class) AccessController.doPrivileged(new PrivilegedAction() { 176 public Object run() { 177 return getGroovyLoader(loader).defineClass(name, bytecode, getClass().getProtectionDomain()); 178 } 179 }); 180 } 181 182 public Class loadClass(final ClassLoader loader, final String name, final byte[] bytecode) throws ClassNotFoundException { 183 return (Class) AccessController.doPrivileged(new PrivilegedAction() { 184 public Object run() { 185 return getGroovyLoader(loader).defineClass(name, bytecode, getClass().getProtectionDomain()); 186 } 187 }); 188 } 189 190 public Class loadClass(ClassLoader loader, String name) throws ClassNotFoundException { 191 return getGroovyLoader(loader).loadClass(name); 192 } 193 194 public Class loadClass(String name) throws ClassNotFoundException { 195 return getGroovyLoader(loader).loadClass(name); 196 } 197 198 private GroovyClassLoader getGroovyLoader(ClassLoader loader) { 199 if (loader instanceof GroovyClassLoader) { 200 return (GroovyClassLoader) loader; 201 } 202 203 synchronized (loaderMap) { 204 GroovyClassLoader groovyLoader = (GroovyClassLoader) loaderMap.get(loader); 205 if (groovyLoader == null) { 206 if (loader == null || loader == getClass().getClassLoader()) { 207 groovyLoader = this.loader; 208 } 209 else { 210 // lets check that the class loader can see the Groovy classes 211 // if so we'll use that, otherwise lets use the local class loader 212 try { 213 loader.loadClass(getClass().getName()); 214 215 // thats fine, lets use the loader 216 groovyLoader = new GroovyClassLoader(loader); 217 } 218 catch (ClassNotFoundException e) { 219 220 // we can't see the groovy classes here 221 // so lets try create a new loader 222 final ClassLoader localLoader = getClass().getClassLoader(); 223 groovyLoader = (GroovyClassLoader) AccessController.doPrivileged(new PrivilegedAction() { 224 public Object run() { 225 return new GroovyClassLoader(localLoader); 226 } 227 }); 228 } 229 } 230 loaderMap.put(loader, groovyLoader); 231 } 232 233 return groovyLoader; 234 } 235 } 236 237 /** 238 * Ensures that all the registered MetaClass instances are initalized 239 */ 240 void checkInitialised() { 241 // lets copy all the classes in the repository right now 242 // to avoid concurrent modification exception 243 List list = new ArrayList(metaClasses.values()); 244 for (Iterator iter = list.iterator(); iter.hasNext();) { 245 MetaClass metaClass = (MetaClass) iter.next(); 246 metaClass.checkInitialised(); 247 } 248 } 249 250 /** 251 * Used by MetaClass when registering new methods which avoids initializing the MetaClass instances on lookup 252 */ 253 MetaClass lookup(Class theClass) { 254 MetaClass answer = (MetaClass) metaClasses.get(theClass); 255 if (answer == null) { 256 answer = getMetaClassFor(theClass); 257 metaClasses.put(theClass, answer); 258 } 259 return answer; 260 } 261 262 /** 263 * Find a MetaClass for the class 264 * If there is a custom MetaClass then return an instance of that. Otherwise return an instance of the standard MetaClass 265 * 266 * @param theClass 267 * @return An instace of the MetaClass which will handle this class 268 */ 269 private MetaClass getMetaClassFor(final Class theClass) { 270 try { 271 final Class customMetaClass = Class.forName("groovy.runtime.metaclass." + theClass.getName() + "MetaClass"); 272 final Constructor customMetaClassConstructor = customMetaClass.getConstructor(new Class[]{MetaClassRegistry.class, Class.class}); 273 274 return (MetaClass)customMetaClassConstructor.newInstance(new Object[]{this, theClass}); 275 } catch (final ClassNotFoundException e) { 276 try { 277 return new MetaClassImpl(this, theClass); 278 } catch (final IntrospectionException e1) { 279 throw new GroovyRuntimeException("Could not introspect class: " + theClass.getName() + ". Reason: " + e1, e1); 280 } 281 } catch (final Exception e) { 282 throw new GroovyRuntimeException("Could not instantiate custom Metaclass for class: " + theClass.getName() + ". Reason: " + e, e); 283 } 284 } 285 286 public MetaMethod getDefinedMethod(Class theClass, String methodName, Class[] args, boolean isStatic) { 287 MetaClass metaclass = this.getMetaClass(theClass); 288 if (metaclass == null) { 289 return null; 290 } 291 else { 292 if (isStatic) { 293 return metaclass.retrieveStaticMethod(methodName, args); 294 } 295 else { 296 return metaclass.retrieveMethod(methodName, args); 297 } 298 } 299 } 300 301 public Constructor getDefinedConstructor(Class theClass, Class[] args) { 302 MetaClass metaclass = this.getMetaClass(theClass); 303 if (metaclass == null) { 304 return null; 305 } 306 else { 307 return metaclass.retrieveConstructor(args); 308 } 309 } 310 311 /** 312 * Singleton of MetaClassRegistry. Shall we use threadlocal to store the instance? 313 * 314 * @param includeExtension 315 * @return 316 */ 317 public static MetaClassRegistry getIntance(int includeExtension) { 318 if (includeExtension != DONT_LOAD_DEFAULT) { 319 if (instanceInclude == null) { 320 instanceInclude = new MetaClassRegistry(); 321 } 322 return instanceInclude; 323 } 324 else { 325 if (instanceExclude == null) { 326 instanceExclude = new MetaClassRegistry(DONT_LOAD_DEFAULT); 327 } 328 return instanceExclude; 329 } 330 } 331 }