@Nullable private MetaMethod findPropertyMissingMethod(MetaClass metaClass) { if (metaClass instanceof MetaClassImpl) { // Reach into meta class to avoid lookup try { return (MetaMethod) MISSING_PROPERTY_GET_METHOD.get(metaClass); } catch (IllegalAccessException e) { throw UncheckedException.throwAsUncheckedException(e); } } // Query the declared methods of the meta class for (MetaMethod method : metaClass.getMethods()) { if (method.getName().equals("propertyMissing") && method.getParameterTypes().length == 1) { return method; } } return null; }
/** * Add listeners to a specific object. Updates the bould flags and update set * * @param listener This listener to attach. * @param newObject The object we should read our property off of. * @param updateSet The list of objects we have added listeners to */ public void addListeners(PropertyChangeListener listener, Object newObject, Set updateSet) { removeListeners(); if (newObject != null) { // check for local synthetics TriggerBinding syntheticTrigger = getSyntheticTriggerBinding(newObject); MetaClass mc = InvokerHelper.getMetaClass(newObject); if (syntheticTrigger != null) { PropertyBinding psb = new PropertyBinding(newObject, propertyName); PropertyChangeProxyTargetBinding proxytb = new PropertyChangeProxyTargetBinding(newObject, propertyName, listener); syntheticFullBinding = syntheticTrigger.createBinding(psb, proxytb); syntheticFullBinding.bind(); updateSet.add(newObject); } else if (!mc.respondsTo(newObject, "addPropertyChangeListener", NAME_PARAMS).isEmpty()) { InvokerHelper.invokeMethod(newObject, "addPropertyChangeListener", new Object[] {propertyName, listener}); localListener = listener; updateSet.add(newObject); } else if (!mc.respondsTo(newObject, "addPropertyChangeListener", GLOBAL_PARAMS).isEmpty()) { InvokerHelper.invokeMethod(newObject, "addPropertyChangeListener", listener); globalListener = listener; updateSet.add(newObject); } } currentObject = newObject; }
private static void staticMethod(final MetaClass self, List<MetaMethod> arr, final CachedMethod method) { CachedClass[] paramTypes = method.getParameterTypes(); if (paramTypes.length == 0) return; NewInstanceMetaMethod metaMethod; if (paramTypes[0].isAssignableFrom(self.getTheClass())) { if (paramTypes[0].getTheClass() == self.getTheClass()) metaMethod = new NewInstanceMetaMethod(method); else metaMethod = new NewInstanceMetaMethod(method) { public CachedClass getDeclaringClass() { return ReflectionCache.getCachedClass(self.getTheClass()); } }; arr.add(metaMethod); } else { if (self.getTheClass().isAssignableFrom(paramTypes[0].getTheClass())) { metaMethod = new NewInstanceMetaMethod(method); arr.add(metaMethod); } } }
public void setNewMopMethods(List<MetaMethod> arr) { final MetaClass metaClass = classInfo.getStrongMetaClass(); if (metaClass != null) { if (metaClass.getClass() == MetaClassImpl.class) { classInfo.setStrongMetaClass(null); updateSetNewMopMethods(arr); classInfo.setStrongMetaClass(new MetaClassImpl(metaClass.getTheClass())); return; } if (metaClass.getClass() == ExpandoMetaClass.class) { classInfo.setStrongMetaClass(null); updateSetNewMopMethods(arr); ExpandoMetaClass newEmc = new ExpandoMetaClass(metaClass.getTheClass()); newEmc.initialize(); classInfo.setStrongMetaClass(newEmc); return; } throw new GroovyRuntimeException("Can't add methods to class " + getTheClass().getName() + ". Strong custom meta class already set."); } classInfo.setWeakMetaClass(null); updateSetNewMopMethods(arr); }
private MetaClass getMetaClassUnderLock() { MetaClass answer = getStrongMetaClass(); if (answer!=null) return answer; answer = getWeakMetaClass(); final MetaClassRegistry metaClassRegistry = GroovySystem.getMetaClassRegistry(); MetaClassRegistry.MetaClassCreationHandle mccHandle = metaClassRegistry.getMetaClassCreationHandler(); if (isValidWeakMetaClass(answer, mccHandle)) { return answer; } answer = mccHandle.create(classRef.get(), metaClassRegistry); answer.initialize(); if (GroovySystem.isKeepJavaMetaClasses()) { setStrongMetaClass(answer); } else { setWeakMetaClass(answer); } return answer; }
private CallSite createPojoMetaClassGetPropertySite(Object receiver) { final MetaClass metaClass = InvokerHelper.getMetaClass(receiver); CallSite site; if (metaClass.getClass() != MetaClassImpl.class || GroovyCategorySupport.hasCategoryInCurrentThread()) { site = new PojoMetaClassGetPropertySite(this); } else { final MetaProperty effective = ((MetaClassImpl) metaClass).getEffectiveGetMetaProperty(receiver.getClass(), receiver, name, false); if (effective != null) { if (effective instanceof CachedField) site = new GetEffectivePojoFieldSite(this, (MetaClassImpl) metaClass, (CachedField) effective); else site = new GetEffectivePojoPropertySite(this, (MetaClassImpl) metaClass, effective); } else { site = new PojoMetaClassGetPropertySite(this); } } array.array[index] = site; return site; }
private CallSite createPogoMetaClassGetPropertySite(GroovyObject receiver) { MetaClass metaClass = receiver.getMetaClass(); CallSite site; if (metaClass.getClass() != MetaClassImpl.class || GroovyCategorySupport.hasCategoryInCurrentThread()) { site = new PogoMetaClassGetPropertySite(this, metaClass); } else { final MetaProperty effective = ((MetaClassImpl) metaClass).getEffectiveGetMetaProperty(this.array.owner, receiver, name, false); if (effective != null) { if (effective instanceof CachedField) site = new GetEffectivePogoFieldSite(this, metaClass, (CachedField) effective); else site = new GetEffectivePogoPropertySite(this, metaClass, effective); } else { site = new PogoMetaClassGetPropertySite(this, metaClass); } } array.array[index] = site; return site; }
private static CallSite createCallStaticSite(CallSite callSite, final Class receiver, Object[] args) { CallSite site; AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { try { Class.forName(receiver.getName(), true, receiver.getClassLoader()); } catch (Exception e) { // force <clinit> } return null; } }); MetaClass metaClass = InvokerHelper.getMetaClass(receiver); if (metaClass instanceof MetaClassImpl) { site = ((MetaClassImpl)metaClass).createStaticSite(callSite, args); } else site = new StaticMetaClassSite(callSite, metaClass); replaceCallSite(callSite, site); return site; }
private static CallSite createCallCurrentSite(CallSite callSite, GroovyObject receiver, Object[] args, Class sender) { CallSite site; if (receiver instanceof GroovyInterceptable) site = new PogoInterceptableSite(callSite); else { MetaClass metaClass = receiver.getMetaClass(); if (receiver.getClass() != metaClass.getTheClass() && !metaClass.getTheClass().isInterface()) { site = new PogoInterceptableSite(callSite); } else if (metaClass instanceof MetaClassImpl) { site = ((MetaClassImpl)metaClass).createPogoCallCurrentSite(callSite, sender, args); } else site = new PogoMetaClassSite(callSite, metaClass); } replaceCallSite(callSite, site); return site; }
/** * Sets the metaclass for a given class. * * @param self the class whose metaclass we wish to set * @param metaClass the new MetaClass * @since 1.6.0 */ public static void setMetaClass(Class self, MetaClass metaClass) { final MetaClassRegistry metaClassRegistry = GroovySystem.getMetaClassRegistry(); if (metaClass == null) metaClassRegistry.removeMetaClass(self); else { if (metaClass instanceof HandleMetaClass) { metaClassRegistry.setMetaClass(self, ((HandleMetaClass)metaClass).getAdaptee()); } else { metaClassRegistry.setMetaClass(self, metaClass); } if (self==NullObject.class) { NullObject.getNullObject().setMetaClass(metaClass); } } }
private static MetaClass hasPerInstanceMetaClass(Object object) { if (object instanceof GroovyObject) { MetaClass mc = ((GroovyObject)object).getMetaClass(); if (mc == GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass()) || mc.getClass() == MetaClassImpl.class) return null; else return mc; } else { ClassInfo info = ClassInfo.getClassInfo(object.getClass()); info.lock(); try { return info.getPerInstanceMetaClass(object); } finally { info.unlock(); } } }
public Object build(Script script) { // this used to be synchronized, but we also used to remove the // metaclass. Since adding the metaclass is now a side effect, we // don't need to ensure the meta-class won't be observed and don't // need to hide the side effect. MetaClass scriptMetaClass = script.getMetaClass(); script.setMetaClass(new FactoryInterceptorMetaClass(scriptMetaClass, this)); script.setBinding(this); Object oldScriptName = getProxyBuilder().getVariables().get(SCRIPT_CLASS_NAME); try { getProxyBuilder().setVariable(SCRIPT_CLASS_NAME, script.getClass().getName()); return script.run(); } finally { if(oldScriptName != null) { getProxyBuilder().setVariable(SCRIPT_CLASS_NAME, oldScriptName); } else { getProxyBuilder().getVariables().remove(SCRIPT_CLASS_NAME); } } }
public void setProperty(String property, Object newValue) { if ("metaClass".equals(property)) { setMetaClass((MetaClass) newValue); } else if ("scriptTarget".equals(property)) { setScriptTarget(newValue); } else { getDynamicTarget().setProperty(property, newValue); } }
private MetaClass getMetaClass() { if (bean instanceof GroovyObject) { return ((GroovyObject) bean).getMetaClass(); } else { return GroovySystem.getMetaClassRegistry().getMetaClass(bean.getClass()); } }
@Nullable protected MetaProperty lookupProperty(MetaClass metaClass, String name) { if (metaClass instanceof MetaClassImpl) { // MetaClass.getMetaProperty(name) is very expensive when the property is not known. Instead, reach into the meta class to call a much more efficient lookup method try { return (MetaProperty) META_PROP_METHOD.invoke(metaClass, name, false); } catch (Throwable e) { throw UncheckedException.throwAsUncheckedException(e); } } // Some other meta-class implementation - fall back to the public API return metaClass.getMetaProperty(name); }
@Nullable @Override protected MetaProperty lookupProperty(MetaClass metaClass, String name) { MetaProperty metaProperty = super.lookupProperty(metaClass, name); if (metaProperty != null) { return metaProperty; } metaProperty = classMetaData.getMetaProperty(name); if (metaProperty != null && Modifier.isStatic(metaProperty.getModifiers())) { return metaProperty; } return null; }
@Nullable @Override protected MetaMethod lookupMethod(MetaClass metaClass, String name, Class[] arguments) { MetaMethod metaMethod = super.lookupMethod(metaClass, name, arguments); if (metaMethod != null) { return metaMethod; } metaMethod = classMetaData.getMetaMethod(name, arguments); if (metaMethod != null && Modifier.isStatic(metaMethod.getModifiers())) { return metaMethod; } return null; }
public void updateConstantMetaClass(final MetaClassRegistryChangeEvent cmcu) { log.info("!! updateConstantMetaClass: {}", cmcu); if (!cleaning) { MetaClass oldMetaClass = cmcu.getOldMetaClass(); Class classToUpdate = cmcu.getClassToUpdate(); Object instanceToUpdate = cmcu.getInstance(); if (instanceToUpdate == null && (cmcu.getNewMetaClass() instanceof ExpandoMetaClass)) { updateMetaClassOfClass(oldMetaClass, classToUpdate); } else if (instanceToUpdate != null) { updateMetaClassOfInstance(oldMetaClass, instanceToUpdate); } } }
private void updateMetaClassOfInstance(MetaClass oldMetaClass, Object instanceToUpdate) { IdentityWeakReference key = new IdentityWeakReference(instanceToUpdate); if (oldMetaClass != null) { Object current = alteredInstances.get(key); if (current == null || current == NO_CUSTOM_METACLASS) { alteredInstances.put(key, oldMetaClass); } } else { alteredInstances.put(key, NO_CUSTOM_METACLASS); } }
private void updateMetaClassOfClass(MetaClass oldMetaClass, Class classToUpdate) { if (oldMetaClass != null && !(oldMetaClass instanceof MockProxyMetaClass)) { Object current = alteredClasses.get(classToUpdate); if (current == null ) { alteredClasses.put(classToUpdate, oldMetaClass); } } else { alteredClasses.put(classToUpdate, NO_CUSTOM_METACLASS); } }
private void cleanMetaClassOfInstance(MetaClassRegistryImpl registry) { List<IdentityWeakReference> keys = new ArrayList<IdentityWeakReference>(alteredInstances.keySet()); for (IdentityWeakReference key : keys) { Object instance = key.get(); if (instance != null) { Object alteredMetaClass = alteredInstances.get(key); if (alteredMetaClass == NO_CUSTOM_METACLASS) { alteredMetaClass = null; } registry.setMetaClass(instance, (MetaClass) alteredMetaClass); } } alteredInstances.clear(); }
private void cleanMetaClassOfClass(MetaClassRegistryImpl registry) { Set<Class> classes = new HashSet<Class>(alteredClasses.keySet()); for (Class aClass : classes) { Object alteredMetaClass = alteredClasses.get(aClass); if (alteredMetaClass == NO_CUSTOM_METACLASS) { registry.removeMetaClass(aClass); } else { registry.setMetaClass(aClass, (MetaClass) alteredMetaClass); } } alteredClasses.clear(); }
/** * Increments the entities version number in order to force an update * @param target The target entity */ public static void incrementVersion(Object target) { MetaClass metaClass = GroovySystem.getMetaClassRegistry().getMetaClass(target.getClass()); if (metaClass.hasProperty(target, GormProperties.VERSION)!=null) { Object version = metaClass.getProperty(target, GormProperties.VERSION); if (version instanceof Long) { Long newVersion = (Long) version + 1; metaClass.setProperty(target, GormProperties.VERSION, newVersion); } } }
private Object createInternal(IMockConfiguration configuration, Specification specification, ClassLoader classLoader) { if (Modifier.isFinal(configuration.getType().getModifiers())) { throw new CannotCreateMockException(configuration.getType(), " because Java mocks cannot mock final classes. If the code under test is written in Groovy, use a Groovy mock."); } if (configuration.isGlobal()) { throw new CannotCreateMockException(configuration.getType(), " because Java mocks cannot mock globally. If the code under test is written in Groovy, use a Groovy mock."); } MetaClass mockMetaClass = GroovyRuntimeUtil.getMetaClass(configuration.getType()); IProxyBasedMockInterceptor interceptor = new JavaMockInterceptor(configuration, specification, mockMetaClass); return ProxyBasedMockFactory.INSTANCE.create(configuration.getType(), Collections.<Class<?>>emptyList(), configuration.getConstructorArgs(), interceptor, classLoader); }
private static boolean notFiltered(Path path, Object filter, Object nameFilter, Object excludeFilter, Object excludeNameFilter) { if (filter == null && nameFilter == null && excludeFilter == null && excludeNameFilter == null) return true; if (filter != null && nameFilter != null) throw new IllegalArgumentException("Can't set both 'filter' and 'nameFilter'"); if (excludeFilter != null && excludeNameFilter != null) throw new IllegalArgumentException("Can't set both 'excludeFilter' and 'excludeNameFilter'"); Object filterToUse = null; Object filterParam = null; if (filter != null) { filterToUse = filter; filterParam = path; } else if (nameFilter != null) { filterToUse = nameFilter; filterParam = path.getFileName().toString(); } Object excludeFilterToUse = null; Object excludeParam = null; if (excludeFilter != null) { excludeFilterToUse = excludeFilter; excludeParam = path; } else if (excludeNameFilter != null) { excludeFilterToUse = excludeNameFilter; excludeParam = path.getFileName().toString(); } final MetaClass filterMC = filterToUse == null ? null : InvokerHelper.getMetaClass(filterToUse); final MetaClass excludeMC = excludeFilterToUse == null ? null : InvokerHelper.getMetaClass(excludeFilterToUse); boolean included = filterToUse == null || DefaultTypeTransformation.castToBoolean(filterMC.invokeMethod(filterToUse, "isCase", filterParam)); boolean excluded = excludeFilterToUse != null && DefaultTypeTransformation.castToBoolean(excludeMC.invokeMethod(excludeFilterToUse, "isCase", excludeParam)); return included && !excluded; }
public static void checkPropNames(Object instance, Map<String, Object> args) { final MetaClass metaClass = InvokerHelper.getMetaClass(instance); for (String k : args.keySet()) { if (metaClass.hasProperty(instance, k) == null) throw new MissingPropertyException(k, instance.getClass()); } }
MetaClass getStaticMetaClass (Object obj) { MetaClass mc; if (staticMetaClass == null || (mc = (MetaClass) staticMetaClass.get()) == null ) { mc = InvokerHelper.getMetaClass(obj); staticMetaClass = new SoftReference(mc); } return mc; }
private static void setMetaClass(final MetaClass metaClass) { final MetaClass newMetaClass = new DelegatingMetaClass(metaClass) { @Override public Object invokeStaticMethod(Object object, String methodName, Object[] arguments) { return InvokerHelper.invokeMethod(INSTANCE, methodName, arguments); } }; GroovySystem.getMetaClassRegistry().setMetaClass(ProxyGenerator.class, newMetaClass); }
public void setWeakMetaClass(MetaClass answer) { version.incrementAndGet(); strongMetaClass = null; ManagedReference<MetaClass> newRef = null; if (answer != null) { newRef = new ManagedReference<MetaClass> (softBundle,answer); } replaceWeakMetaClassRef(newRef); }
private void replaceWeakMetaClassRef(ManagedReference<MetaClass> newRef) { // safe value here to avoid multiple reads with possibly // differing values due to concurrency ManagedReference<MetaClass> weakRef = weakMetaClass; if (weakRef != null) { weakRef.clear(); } weakMetaClass = newRef; }
public MetaClass getMetaClassForClass() { // safe value here to avoid multiple reads with possibly // differing values due to concurrency MetaClass strongMc = strongMetaClass; if (strongMc!=null) return strongMc; MetaClass weakMc = getWeakMetaClass(); if (isValidWeakMetaClass(weakMc)) { return weakMc; } return null; }
public static Object invokeSuperMethod(Object object, String methodName, Object arguments) { if (object == null) { throw new NullPointerException("Cannot invoke method " + methodName + "() on null object"); } Class theClass = object.getClass(); MetaClass metaClass = metaRegistry.getMetaClass(theClass.getSuperclass()); return metaClass.invokeMethod(object, methodName, asArray(arguments)); }
private Object autoInstantiateDomainInstance(Class<?> type) { Object created = null; try { MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(type); if (mc != null) { created = mc.invokeStaticMethod(type, CreateDynamicMethod.METHOD_NAME, new Object[0]); } } catch (MissingMethodException mme) { LOG.warn("Unable to auto-create type, 'create' method not found"); } catch (GroovyRuntimeException gre) { LOG.warn("Unable to auto-create type, Groovy Runtime error: " + gre.getMessage(), gre); } return created; }
/** * Returns the MetaClassImpl if the given MetaClass is one of * MetaClassImpl, AdaptingMetaClass or ClosureMetaClass. If * none of these cases matches, this method returns null. */ private static MetaClassImpl getMetaClassImpl(MetaClass mc, boolean includeEMC) { Class mcc = mc.getClass(); boolean valid = mcc == MetaClassImpl.class || mcc == AdaptingMetaClass.class || mcc == ClosureMetaClass.class || (includeEMC && mcc == ExpandoMetaClass.class); if (!valid) { if (LOG_ENABLED) LOG.info("meta class is neither MetaClassImpl, nor AdoptingMetaClass, nor ClosureMetaClass, normal method selection path disabled."); return null; } if (LOG_ENABLED) LOG.info("meta class is a recognized MetaClassImpl"); return (MetaClassImpl) mc; }
private static CallSite createCallConstructorSite(CallSite callSite, Class receiver, Object[] args) { MetaClass metaClass = InvokerHelper.getMetaClass(receiver); CallSite site; if (metaClass instanceof MetaClassImpl) { site = ((MetaClassImpl)metaClass).createConstructorSite(callSite, args); } else site = new MetaClassConstructorSite(callSite, metaClass); replaceCallSite(callSite, site); return site; }
private static CallSite createPogoSite(CallSite callSite, Object receiver, Object[] args) { if (receiver instanceof GroovyInterceptable) return new PogoInterceptableSite(callSite); MetaClass metaClass = ((GroovyObject)receiver).getMetaClass(); if (metaClass instanceof MetaClassImpl) { return ((MetaClassImpl)metaClass).createPogoCallSite(callSite, args); } return new PogoMetaClassSite(callSite, metaClass); }
public static Object invokeMethodOnSuperN(Class senderClass, GroovyObject receiver, String messageName, Object[] messageArguments) throws Throwable { MetaClass metaClass = receiver.getMetaClass(); // ignore interception and missing method fallback Object result = null; try { result = metaClass.invokeMethod(senderClass, receiver, messageName, messageArguments, true, true); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } return result; }
public static int selectConstructorAndTransformArguments(Object[] arguments, int numberOfConstructors, Class which) throws Throwable { MetaClass metaClass = GroovySystem.getMetaClassRegistry().getMetaClass(which); try { return metaClass.selectConstructorAndTransformArguments(numberOfConstructors, arguments); } catch (GroovyRuntimeException gre) { throw unwrap(gre); } }
public static Object getFieldOnSuper(Class senderClass, Object receiver, String messageName) throws Throwable { try { if (receiver instanceof Class) { return InvokerHelper.getAttribute(receiver, messageName); } else { MetaClass mc = ((GroovyObject) receiver).getMetaClass(); return mc.getAttribute(senderClass, receiver, messageName, true); } } catch (GroovyRuntimeException gre) { throw unwrap(gre); } }
public static void setFieldOnSuper(Object messageArgument, Class senderClass, Object receiver, String messageName) throws Throwable { try { if (receiver instanceof Class) { InvokerHelper.setAttribute(receiver, messageName, messageArgument); } else { MetaClass mc = ((GroovyObject) receiver).getMetaClass(); mc.setAttribute(senderClass, receiver, messageName, messageArgument, true, true); } } catch (GroovyRuntimeException gre) { throw unwrap(gre); } }