groovy.lang.MetaClass Java Examples

The following examples show how to use groovy.lang.MetaClass. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FactoryBuilderSupport.java    From groovy with Apache License 2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example #2
Source File: MetaElementsProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Map<FieldSignature, CompletionItem> getFields(CompletionContext context) {
    final Map<FieldSignature, CompletionItem> result = new HashMap<FieldSignature, CompletionItem>();
    final Class<?> clazz = loadClass(context);
    
    if (clazz != null) {
        final MetaClass metaClass = GroovySystem.getMetaClassRegistry().getMetaClass(clazz);

        if (metaClass != null) {
            
            for (Object field : metaClass.getProperties()) {
                MetaProperty prop = (MetaProperty) field;
                if (prop.getName().startsWith(context.getPrefix())) {
                    result.put(new FieldSignature(prop.getName()), new CompletionItem.FieldItem(
                            prop.getType().getSimpleName(),
                            prop.getName(),
                            prop.getModifiers(),
                            context.getAnchor()));
                }
            }
            GroovySystem.getMetaClassRegistry().removeMetaClass(clazz);
        }
    }
    
    return result;
}
 
Example #3
Source File: MetaElementsProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Map<MethodSignature, CompletionItem> getStaticMethods(CompletionContext context) {
    final Map<MethodSignature, CompletionItem> result = new HashMap<MethodSignature, CompletionItem>();
    final Class clz = loadClass(context);

    if (clz != null) {
        final MetaClass metaClz = GroovySystem.getMetaClassRegistry().getMetaClass(clz);

        if (metaClz != null) {
            for (MetaMethod method : metaClz.getMetaMethods()) {
                if (method.isStatic()) {
                    populateProposal(clz, method, context.getPrefix(), context.getAnchor(), result, context.isNameOnly());
                }
            }
        }
        GroovySystem.getMetaClassRegistry().removeMetaClass(clz);
    }
    return result;
}
 
Example #4
Source File: InvokerHelper.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Invokes the given method on the object.
 */
public static Object invokeMethod(Object object, String methodName, Object arguments) {
    if (object == null) {
        object = NullObject.getNullObject();
        //throw new NullPointerException("Cannot invoke method " + methodName + "() on null object");
    }

    // if the object is a Class, call a static method from that class
    if (object instanceof Class) {
        Class theClass = (Class) object;
        MetaClass metaClass = metaRegistry.getMetaClass(theClass);
        return metaClass.invokeStaticMethod(object, methodName, asArray(arguments));
    }

    // it's an instance; check if it's a Java one
    if (!(object instanceof GroovyObject)) {
        return invokePojoMethod(object, methodName, arguments);
    }

    // a groovy instance (including builder, closure, ...)
    return invokePogoMethod(object, methodName, arguments);
}
 
Example #5
Source File: AbstractCallSite.java    From groovy with Apache License 2.0 6 votes vote down vote up
private CallSite createPojoMetaClassGetPropertySite(final 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;
}
 
Example #6
Source File: BindPath.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #7
Source File: CallSiteArray.java    From groovy with Apache License 2.0 6 votes vote down vote up
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();
        Class theClass = metaClass.getTheClass();
        if (receiver.getClass() != theClass && !theClass.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;
}
 
Example #8
Source File: MetaClassRegistryImpl.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * if oldMc is null, newMc will replace whatever meta class was used before.
 * if oldMc is not null, then newMc will be used only if the stored mc is
 * the same as oldMc
 */
private void setMetaClass(Class theClass, MetaClass oldMc, MetaClass newMc) {
    final ClassInfo info = ClassInfo.getClassInfo(theClass);
    
    MetaClass mc = null;
    info.lock();
    try {
        mc = info.getStrongMetaClass();
        info.setStrongMetaClass(newMc);
    } finally {
        info.unlock();
    }
    if ((oldMc == null && mc != newMc) || (oldMc != null && mc != newMc && mc != oldMc)) {
        fireConstantMetaClassUpdate(null, theClass, mc, newMc);
    }
}
 
Example #9
Source File: Inspector.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Get info about instance and class Methods that are dynamically added through Groovy.
 *
 * @return Array of StringArrays that can be indexed with the MEMBER_xxx_IDX constants
 */
public Object[] getMetaMethods() {
    MetaClass metaClass = InvokerHelper.getMetaClass(objectUnderInspection);
    List metaMethods = metaClass.getMetaMethods();
    Object[] result = new Object[metaMethods.size()];
    int i = 0;
    for (Iterator iter = metaMethods.iterator(); iter.hasNext(); i++) {
        MetaMethod metaMethod = (MetaMethod) iter.next();
        result[i] = methodInfo(metaMethod);
    }
    return result;
}
 
Example #10
Source File: DefaultInvoker.java    From groovy-cps with Apache License 2.0 5 votes vote down vote up
public Object superCall(Class methodType, Object receiver, String method, Object[] args) throws Throwable {
    try {
        MetaClass mc = InvokerHelper.getMetaClass(receiver.getClass());
        return mc.invokeMethod(methodType.getSuperclass(), receiver, method, args, true, true);
    } catch (GroovyRuntimeException gre) {
        throw ScriptBytecodeAdapter.unwrap(gre);
    }
}
 
Example #11
Source File: SpringDocGroovyConfiguration.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Ignore groovy meta class object.
 *
 * @return the object
 */
@Bean
@Lazy(false)
Object ignoreGroovyMetaClass() {
	SpringDocUtils.getConfig().addRequestWrapperToIgnore(MetaClass.class);
	return null;
}
 
Example #12
Source File: ScriptBytecodeAdapter.java    From groovy with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #13
Source File: ResourceGroovyMethods.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static boolean notFiltered(File file, 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 = file;
    } else if (nameFilter != null) {
        filterToUse = nameFilter;
        filterParam = file.getName();
    }
    Object excludeFilterToUse = null;
    Object excludeParam = null;
    if (excludeFilter != null) {
        excludeFilterToUse = excludeFilter;
        excludeParam = file;
    } else if (excludeNameFilter != null) {
        excludeFilterToUse = excludeNameFilter;
        excludeParam = file.getName();
    }
    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;
}
 
Example #14
Source File: ConversionHandler.java    From groovy with Apache License 2.0 5 votes vote down vote up
private MetaClass getMetaClass(Object proxy) {
    MetaClass mc = metaClass;
    if (mc == null) {
        mc = ((MetaClassRegistryImpl) GroovySystem.getMetaClassRegistry()).getMetaClass(proxy);
        metaClass = mc;
    }
    return mc;
}
 
Example #15
Source File: Selector.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #16
Source File: GrailsDataBinder.java    From AlgoTrader with GNU General Public License v2.0 5 votes vote down vote up
private void addAssociationToTarget(String name, Object target, Object obj) {
	if (obj == null) {
		return;
	}

	MetaClassRegistry reg = GroovySystem.getMetaClassRegistry();
	MetaClass mc = reg.getMetaClass(target.getClass());
	final String addMethodName = "addTo" + GrailsNameUtils.getClassNameRepresentation(name);
	mc.invokeMethod(target, addMethodName, obj);
}
 
Example #17
Source File: ClassInfo.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void setPerInstanceMetaClass(Object obj, MetaClass metaClass) {
    version.incrementAndGet();

    if (metaClass != null) {
        if (perInstanceMetaClassMap == null)
          perInstanceMetaClassMap = new ManagedConcurrentMap<Object, MetaClass>(ReferenceBundle.getWeakBundle());

        perInstanceMetaClassMap.put(obj, metaClass);
    }
    else {
        if (perInstanceMetaClassMap != null) {
          perInstanceMetaClassMap.remove(obj);
        }
    }
}
 
Example #18
Source File: CallSiteArray.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static CallSite createCallConstructorSite(CallSite callSite, Class receiver, Object[] args) {
    MetaClass metaClass = InvokerHelper.getMetaClass(receiver);
    CallSite site =
            metaClass instanceof MetaClassImpl
                    ? ((MetaClassImpl) metaClass).createConstructorSite(callSite, args)
                    : new MetaClassConstructorSite(callSite, metaClass);

    replaceCallSite(callSite, site);
    return site;
}
 
Example #19
Source File: ProxyGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #20
Source File: ClassInfo.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * if EMC.enableGlobally() is OFF, return whatever the cached answer is.
 * but if EMC.enableGlobally() is ON and the cached answer is not an EMC, come up with a fresh answer
 */
private static boolean isValidWeakMetaClass(MetaClass metaClass, MetaClassRegistry.MetaClassCreationHandle mccHandle) {
    if(metaClass==null) return false;
    boolean enableGloballyOn = (mccHandle instanceof ExpandoMetaClassCreationHandle);
    boolean cachedAnswerIsEMC = (metaClass instanceof ExpandoMetaClass);
    return (!enableGloballyOn || cachedAnswerIsEMC);
}
 
Example #21
Source File: InvokerHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void setPropertySafe(Object object, MetaClass mc, String key, Object value) {
    try {
        mc.setProperty(object, key, value);
    } catch (MissingPropertyException mpe) {
        // Ignore
    } catch (InvokerInvocationException iie) {
        // GROOVY-5802 IAE for missing properties with classes that extend List
        Throwable cause = iie.getCause();
        if (!(cause instanceof IllegalArgumentException)) throw iie;
    }
}
 
Example #22
Source File: GrailsHibernateUtil.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example #23
Source File: GrailsDataBinder.java    From AlgoTrader with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #24
Source File: ImmutableASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
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());
    }
}
 
Example #25
Source File: CachedClass.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void setNewMopMethods(List<MetaMethod> arr) {
    final MetaClass metaClass = classInfo.getStrongMetaClass();
    if (metaClass != null) {
      if (metaClass.getClass() == MetaClassImpl.class) {
          classInfo.setStrongMetaClass(null);
          updateSetNewMopMethods(arr);
          MetaClassImpl mci = new MetaClassImpl(metaClass.getTheClass());
          mci.initialize();
          classInfo.setStrongMetaClass(mci);
          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);
}
 
Example #26
Source File: HandleMetaClass.java    From groovy with Apache License 2.0 5 votes vote down vote up
public HandleMetaClass(MetaClass mc, Object obj) {
    super(mc);
    if (obj != null) {
        if (InvokerHelper.getMetaClass(obj.getClass()) == mc || !(mc instanceof ExpandoMetaClass))
          object = obj; // object has default meta class, so we need to replace it on demand
        else
          object = NONE; // object already has per instance meta class
    }
}
 
Example #27
Source File: ClassInfo.java    From groovy with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #28
Source File: ClassInfo.java    From groovy with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #29
Source File: OwnedMetaClass.java    From groovy with Apache License 2.0 4 votes vote down vote up
public void setAttribute(Object object, String attribute, Object newValue) {
    final Object owner = getOwner();
    final MetaClass ownerMetaClass = getOwnerMetaClass(owner);
    ownerMetaClass.setAttribute(object, attribute, newValue);
}
 
Example #30
Source File: MockProxyMetaClass.java    From groovy with Apache License 2.0 4 votes vote down vote up
/**
 * @param adaptee the MetaClass to decorate with interceptability
 */
public MockProxyMetaClass(MetaClassRegistry registry, Class theClass, MetaClass adaptee) {
    this(registry, theClass, adaptee, false);
}