Java源码示例:groovy.lang.MetaProperty

示例1
@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;
}
 
示例2
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;
}
 
示例3
private CallSite createPogoMetaClassGetPropertySite(final 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;
}
 
示例4
/**
 * 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(): "";
}
 
示例5
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);
        }
    }
}
 
示例6
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;
      }
  };
}
 
示例7
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));
        }
    };
}
 
示例8
/**
 * 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;
}
 
示例9
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);
        }
    }
}
 
示例10
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]);
}
 
示例11
/**
 * 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);
}
 
示例12
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;
}
 
示例13
public static String getSetterName(final String name) {
    return MetaProperty.getSetterName(name);
}
 
示例14
public GetEffectivePojoPropertySite(CallSite site, MetaClassImpl metaClass, MetaProperty effective) {
    super(site);
    this.metaClass = metaClass;
    this.effective = effective;
    version = metaClass.getVersion();
}
 
示例15
public GetEffectivePogoPropertySite(CallSite site, MetaClass metaClass, MetaProperty effective) {
    super(site);
    this.metaClass = metaClass;
    this.effective = effective;
}
 
示例16
public RankableField(String name, MetaProperty mp) {
    this.f = mp;
    this.score = delDistance(name,mp.getName());
}
 
示例17
public MetaProperty getMetaProperty(String name) {
    return CLOSURE_METACLASS.getMetaProperty(name);
}
 
示例18
@Override
public List<MetaProperty> getProperties() {
    return CLOSURE_METACLASS.getProperties();
}
 
示例19
public MetaProperty hasProperty(Object obj, String name) {
    final Object owner = getOwner();
    final MetaClass ownerMetaClass = getOwnerMetaClass(owner);
    return ownerMetaClass.hasProperty(owner, name);
}
 
示例20
public List<MetaProperty> getProperties() {
    final Object owner = getOwner();
    final MetaClass ownerMetaClass = getOwnerMetaClass(owner);
    return ownerMetaClass.getProperties();
}
 
示例21
public MetaProperty getMetaProperty(String name) {
    final Object owner = getOwner();
    final MetaClass ownerMetaClass = getOwnerMetaClass(owner);
    return ownerMetaClass.getMetaProperty(name);
}
 
示例22
public MixinInstanceMetaProperty(MetaProperty property, MixinInMetaClass mixinInMetaClass) {
    super(property.getName(), property.getType(), createGetter(property, mixinInMetaClass), createSetter(property, mixinInMetaClass));
}
 
示例23
public MultipleSetterProperty(String name) {
    super(name, Object.class);
    this.setterName = MetaProperty.getSetterName(name);
}
 
示例24
/**
 * 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();
        try {
            Method reflectionMethod = aClass.getMethod("getProperty", String.class);
            if (!reflectionMethod.isSynthetic() && !isMarkedInternal(reflectionMethod)) {
                handle = MethodHandles.insertArguments(GROOVY_OBJECT_GET_PROPERTY, 1, name);
                return;
            }
        } catch (ReflectiveOperationException ignored) {
        }
    } 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.getCachedField();
        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);
    }
}