public Map<String, ?> getProperties() { if (!includeProperties) { return Collections.emptyMap(); } Map<String, Object> properties = new HashMap<String, Object>(); List<MetaProperty> classProperties = getMetaClass().getProperties(); for (MetaProperty metaProperty : classProperties) { if (metaProperty.getName().equals("properties")) { properties.put("properties", properties); continue; } if (metaProperty instanceof MetaBeanProperty) { MetaBeanProperty beanProperty = (MetaBeanProperty) metaProperty; if (beanProperty.getGetter() == null) { continue; } } properties.put(metaProperty.getName(), metaProperty.getProperty(bean)); } getOpaqueProperties(properties); return properties; }
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; }
/** * Returns a string detailing possible solutions to a missing field or property * if no good solutions can be found a empty string is returned. * * @param fieldName the missing field * @param type the class on which the field is sought * @return a string with probable solutions to the exception */ public static String getPropertySuggestionString(String fieldName, Class type){ ClassInfo ci = ClassInfo.getClassInfo(type); List<MetaProperty> fi = ci.getMetaClass().getProperties(); List<RankableField> rf = new ArrayList<RankableField>(fi.size()); StringBuilder sb = new StringBuilder(); sb.append("\nPossible solutions: "); for(MetaProperty mp : fi) rf.add(new RankableField(fieldName, mp)); Collections.sort(rf); int i = 0; for (RankableField f : rf) { if (i > MAX_RECOMENDATIONS) break; if (f.score > MAX_FIELD_SCORE) break; if(i > 0) sb.append(", "); sb.append(f.f.getName()); i++; } return i > 0? sb.toString(): ""; }
public void setChild(FactoryBuilderSupport builder, Object parent, Object child) { if (child == null) return; ObjectGraphBuilder ogbuilder = (ObjectGraphBuilder) builder; if (parent != null) { Map context = ogbuilder.getContext(); Map parentContext = ogbuilder.getParentContext(); String parentName = null; String childName = (String) context.get(NODE_NAME); if (parentContext != null) { parentName = (String) parentContext.get(NODE_NAME); } String propertyName = ogbuilder.relationNameResolver.resolveParentRelationName( parentName, parent, childName, child); MetaProperty metaProperty = InvokerHelper.getMetaClass(child) .hasProperty(child, propertyName); if (metaProperty != null) { metaProperty.setProperty(child, parent); } } }
private Map resolveConstrainedProperties(Object object, GrailsDomainClass dc) { Map constrainedProperties = null; if (dc != null) { constrainedProperties = dc.getConstrainedProperties(); } else { // is this dead code? , didn't remove in case it's used somewhere MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass()); MetaProperty metaProp = mc.getMetaProperty(CONSTRAINTS_PROPERTY); if (metaProp != null) { Object constrainedPropsObj = getMetaPropertyValue(metaProp, object); if (constrainedPropsObj instanceof Map) { constrainedProperties = (Map) constrainedPropsObj; } } } return constrainedProperties; }
@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; }
private static MetaMethod createSetter(final MetaProperty property, final MixinInMetaClass mixinInMetaClass) { return new MetaMethod() { final String name = getSetterName(property.getName()); { setParametersTypes (new CachedClass [] {ReflectionCache.getCachedClass(property.getType())} ); } public int getModifiers() { return Modifier.PUBLIC; } public String getName() { return name; } public Class getReturnType() { return property.getType(); } public CachedClass getDeclaringClass() { return mixinInMetaClass.getInstanceClass(); } public Object invoke(Object object, Object[] arguments) { property.setProperty(mixinInMetaClass.getMixinInstance(object), arguments[0]); return null; } }; }
private static MetaMethod createGetter(final MetaProperty property, final MixinInMetaClass mixinInMetaClass) { return new MetaMethod() { final String name = getGetterName(property.getName(), property.getType()); { setParametersTypes (CachedClass.EMPTY_ARRAY); } public int getModifiers() { return Modifier.PUBLIC; } public String getName() { return name; } public Class getReturnType() { return property.getType(); } public CachedClass getDeclaringClass() { return mixinInMetaClass.getInstanceClass(); } public Object invoke(Object object, Object[] arguments) { return property.getProperty(mixinInMetaClass.getMixinInstance(object)); } }; }
/** * Handles the common English regular plurals with the following rules. * <ul> * <li>If childName ends in {consonant}y, replace 'y' with "ies". For example, allergy to allergies.</li> * <li>Otherwise, append 's'. For example, monkey to monkeys; employee to employees.</li> * </ul> * If the property does not exist then it will return childName unchanged. * * @see <a href="http://en.wikipedia.org/wiki/English_plural">English_plural</a> */ public String resolveChildRelationName(String parentName, Object parent, String childName, Object child) { boolean matchesIESRule = PLURAL_IES_PATTERN.matcher(childName).matches(); String childNamePlural = matchesIESRule ? childName.substring(0, childName.length() - 1) + "ies" : childName + "s"; MetaProperty metaProperty = InvokerHelper.getMetaClass(parent) .hasProperty(parent, childNamePlural); return metaProperty != null ? childNamePlural : childName; }
private void resolveLazyReferences() { if (!lazyReferencesAllowed) return; for (NodeReference ref : lazyReferences) { if (ref.parent == null) continue; Object child = null; try { child = getProperty(ref.refId); } catch (MissingPropertyException mpe) { // ignore } if (child == null) { throw new IllegalArgumentException("There is no valid node for reference " + ref.parentName + "." + ref.childName + "=" + ref.refId); } // set child first childPropertySetter.setChild(ref.parent, child, ref.parentName, relationNameResolver.resolveChildRelationName(ref.parentName, ref.parent, ref.childName, child)); // set parent afterwards String propertyName = relationNameResolver.resolveParentRelationName(ref.parentName, ref.parent, ref.childName, child); MetaProperty metaProperty = InvokerHelper.getMetaClass(child) .hasProperty(child, propertyName); if (metaProperty != null) { metaProperty.setProperty(child, ref.parent); } } }
public void testInspectUninspectableProperty() { Object dummyInstance = new Object(); Inspector inspector = getTestableInspector(dummyInstance); Class[] paramTypes = {Object.class, MetaProperty.class}; Object[] params = {null, null}; Mock mock = mock(PropertyValue.class, paramTypes, params); mock.expects(once()).method("getType"); mock.expects(once()).method("getName"); mock.expects(once()).method("getValue").will(throwException(new RuntimeException())); PropertyValue propertyValue = (PropertyValue) mock.proxy(); String[] result = inspector.fieldInfo(propertyValue); assertEquals(Inspector.NOT_APPLICABLE, result[Inspector.MEMBER_VALUE_IDX]); }
/** * Hack because of bug in ThreadManagedMetaBeanProperty, http://jira.codehaus.org/browse/GROOVY-3723 , fixed since 1.6.5 * * @param metaProperty * @param delegate * @return */ private Object getMetaPropertyValue(MetaProperty metaProperty, Object delegate) { if (metaProperty instanceof ThreadManagedMetaBeanProperty) { return ((ThreadManagedMetaBeanProperty) metaProperty).getGetter().invoke(delegate, MetaClassHelper.EMPTY_ARRAY); } return metaProperty.getProperty(delegate); }
@Test(groups = { TestGroups.UNIT }) public void hasFieldTest() { class TestClass { @SuppressWarnings("unused") public Object a = new Object(); } Assert.assertTrue(DefaultGroovyMethods.hasProperty(TestClass.class, "a") == null); Assert.assertTrue(ClassUtil.hasField(TestClass.class, "a") instanceof MetaProperty); Assert.assertFalse(ClassUtil.hasField(TestClass.class, "b") instanceof MetaProperty); Assert.assertTrue(ClassUtil.hasField(TestClass.class, "b") == null); }
private void initGroovyCommands(final ScriptEngine scriptEngine, final ScriptContext scriptContext) { Commands commands = new Commands(scriptContext); for (MetaProperty mp : commands.getMetaClass().getProperties()) { String propertyType = mp.getType().getCanonicalName(); String propertyName = mp.getName(); if (propertyType.equals(groovy.lang.Closure.class.getCanonicalName())) { scriptEngine.put(propertyName, commands.getProperty(propertyName)); } } }
public void setProperty(final String name, Object value, SetPropertyResult result) { if (!includeProperties) { return; } MetaClass metaClass = getMetaClass(); MetaProperty property = lookupProperty(metaClass, name); if (property != null) { if (property instanceof MultipleSetterProperty) { // Invoke the setter method, to pick up type coercion String setterName = MetaProperty.getSetterName(property.getName()); InvokeMethodResult setterResult = new InvokeMethodResult(); invokeMethod(setterName, setterResult, value); if (setterResult.isFound()) { result.found(); return; } } else { if (property instanceof MetaBeanProperty) { MetaBeanProperty metaBeanProperty = (MetaBeanProperty) property; if (metaBeanProperty.getSetter() == null) { if (metaBeanProperty.getField() == null) { throw setReadOnlyProperty(name); } value = propertySetTransformer.transformValue(metaBeanProperty.getField().getType(), value); metaBeanProperty.getField().setProperty(bean, value); } else { // Coerce the value to the type accepted by the property setter and invoke the setter directly Class setterType = metaBeanProperty.getSetter().getParameterTypes()[0].getTheClass(); value = propertySetTransformer.transformValue(setterType, value); value = DefaultTypeTransformation.castToType(value, setterType); metaBeanProperty.getSetter().invoke(bean, new Object[]{value}); } } else { // Coerce the value to the property type, if known value = propertySetTransformer.transformValue(property.getType(), value); property.setProperty(bean, value); } result.found(); return; } } if (!implementsMissing) { return; } try { setOpaqueProperty(metaClass, name, value); result.found(); } catch (MissingPropertyException e) { if (!name.equals(e.getProperty())) { throw e; } } }
private Expression transformBinaryExpression(final BinaryExpression exp) { Expression trn = super.transform(exp); if (trn instanceof BinaryExpression) { BinaryExpression bin = (BinaryExpression) trn; Expression leftExpression = bin.getLeftExpression(); if (bin.getOperation().getType() == Types.EQUAL && leftExpression instanceof PropertyExpression) { ClassNode traitReceiver = null; PropertyExpression leftPropertyExpression = (PropertyExpression) leftExpression; if (isTraitSuperPropertyExpression(leftPropertyExpression.getObjectExpression())) { PropertyExpression pexp = (PropertyExpression) leftPropertyExpression.getObjectExpression(); traitReceiver = pexp.getObjectExpression().getType(); } if (traitReceiver!=null) { // A.super.foo = ... TraitHelpersTuple helpers = Traits.findHelpers(traitReceiver); ClassNode helper = helpers.getHelper(); String setterName = MetaProperty.getSetterName(leftPropertyExpression.getPropertyAsString()); List<MethodNode> methods = helper.getMethods(setterName); for (MethodNode method : methods) { Parameter[] parameters = method.getParameters(); if (parameters.length==2 && parameters[0].getType().equals(traitReceiver)) { ArgumentListExpression args = new ArgumentListExpression( new VariableExpression("this"), transform(exp.getRightExpression()) ); MethodCallExpression setterCall = new MethodCallExpression( new ClassExpression(helper), setterName, args ); setterCall.setMethodTarget(method); setterCall.setImplicitThis(false); return setterCall; } } return bin; } } } return trn; }
public GetEffectivePojoPropertySite(CallSite site, MetaClassImpl metaClass, MetaProperty effective) { super(site); this.metaClass = metaClass; this.effective = effective; version = metaClass.getVersion(); }
public GetEffectivePogoPropertySite(CallSite site, MetaClass metaClass, MetaProperty effective) { super(site); this.metaClass = metaClass; this.effective = effective; }
public RankableField(String name, MetaProperty mp) { this.f = mp; this.score = delDistance(name,mp.getName()); }
public MetaProperty getMetaProperty(String name) { return CLOSURE_METACLASS.getMetaProperty(name); }
@Override public List<MetaProperty> getProperties() { return CLOSURE_METACLASS.getProperties(); }
public MetaProperty hasProperty(Object obj, String name) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.hasProperty(owner, name); }
public List<MetaProperty> getProperties() { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.getProperties(); }
public MetaProperty getMetaProperty(String name) { final Object owner = getOwner(); final MetaClass ownerMetaClass = getOwnerMetaClass(owner); return ownerMetaClass.getMetaProperty(name); }
public MixinInstanceMetaProperty(MetaProperty property, MixinInMetaClass mixinInMetaClass) { super(property.getName(), property.getType(), createGetter(property, mixinInMetaClass), createSetter(property, mixinInMetaClass)); }
public MultipleSetterProperty(String name) { super(name, Object.class); this.setterName = MetaProperty.getSetterName(name); }
/** * this method chooses a property from the meta class. */ @Override public void chooseMeta(MetaClassImpl mci) { Object receiver = getCorrectedReceiver(); if (receiver instanceof GroovyObject) { Class aClass = receiver.getClass(); Method reflectionMethod = null; try { reflectionMethod = aClass.getMethod("getProperty", String.class); if (!reflectionMethod.isSynthetic()) { handle = MethodHandles.insertArguments(GROOVY_OBJECT_GET_PROPERTY, 1, name); return; } } catch (ReflectiveOperationException e) {} } else if (receiver instanceof Class) { handle = MOP_GET; handle = MethodHandles.insertArguments(handle, 2, name); handle = MethodHandles.insertArguments(handle, 0, this.mc); return; } if (method!=null || mci==null) return; Class chosenSender = this.sender; if (mci.getTheClass()!= chosenSender && GroovyCategorySupport.hasCategoryInCurrentThread()) { chosenSender = mci.getTheClass(); } MetaProperty res = mci.getEffectiveGetMetaProperty(chosenSender, receiver, name, false); if (res instanceof MethodMetaProperty) { MethodMetaProperty mmp = (MethodMetaProperty) res; method = mmp.getMetaMethod(); insertName = true; } else if (res instanceof CachedField) { CachedField cf = (CachedField) res; Field f = cf.field; try { handle = LOOKUP.unreflectGetter(f); if (Modifier.isStatic(f.getModifiers())) { // normally we would do the following // handle = MethodHandles.dropArguments(handle,0,Class.class); // but because there is a bug in invokedynamic in all jdk7 versions // maybe use Unsafe.ensureClassInitialized handle = META_PROPERTY_GETTER.bindTo(res); } } catch (IllegalAccessException iae) { throw new GroovyBugError(iae); } } else { handle = META_PROPERTY_GETTER.bindTo(res); } }
/** * Retrieves the list of {@link groovy.lang.MetaProperty} objects for 'self' and wraps it * in a list of {@link groovy.lang.PropertyValue} objects that additionally provide * the value for each property of 'self'. * * @param self the receiver object * @return list of {@link groovy.lang.PropertyValue} objects * @see groovy.util.Expando#getMetaPropertyValues() * @since 1.0 */ public static List<PropertyValue> getMetaPropertyValues(Object self) { MetaClass metaClass = InvokerHelper.getMetaClass(self); List<MetaProperty> mps = metaClass.getProperties(); List<PropertyValue> props = new ArrayList<PropertyValue>(mps.size()); for (MetaProperty mp : mps) { props.add(new PropertyValue(self, mp)); } return props; }
/** * <p>Returns true of the implementing MetaClass has a property of the given name * * <p>Note that this method will only return true for realised properties and does not take into * account implementation of getProperty or propertyMissing * * @param self The object to inspect * @param name The name of the property of interest * @return The found MetaProperty or null if it doesn't exist * @see groovy.lang.MetaObjectProtocol#hasProperty(java.lang.Object, java.lang.String) * @since 1.6.1 */ public static MetaProperty hasProperty(Object self, String name) { return InvokerHelper.getMetaClass(self).hasProperty(self, name); }