Example usage for java.lang.reflect Field getDeclaringClass

List of usage examples for java.lang.reflect Field getDeclaringClass

Introduction

In this page you can find the example usage for java.lang.reflect Field getDeclaringClass.

Prototype

@Override
public Class<?> getDeclaringClass() 

Source Link

Document

Returns the Class object representing the class or interface that declares the field represented by this Field object.

Usage

From source file:org.openmrs.module.sync.SyncUtil.java

public static Object valForField(String fieldName, String fieldVal, ArrayList<Field> allFields, Node n) {
    Object o = null;//w  ww . j  a  v  a2  s .co m

    // the String value on the node specifying the "type"
    String nodeDefinedClassName = null;
    if (n != null) {
        Node tmpNode = n.getAttributes().getNamedItem("type");
        if (tmpNode != null)
            nodeDefinedClassName = tmpNode.getTextContent();
    }

    // TODO: Speed up sync by passing in a Map of String fieldNames instead of list of Fields ? 
    // TODO: Speed up sync by returning after "o" is first set?  Or are we doing "last field wins" ?
    for (Field f : allFields) {
        //log.debug("field is " + f.getName());
        if (f.getName().equals(fieldName)) {
            Class classType = null;
            String className = f.getGenericType().toString(); // the string class name for the actual field

            // if its a collection, set, list, etc
            if (ParameterizedType.class.isAssignableFrom(f.getGenericType().getClass())) {
                ParameterizedType pType = (ParameterizedType) f.getGenericType();
                classType = (Class) pType.getRawType(); // can this be anything but Class at this point?!
            }

            if (className.startsWith("class ")) {
                className = className.substring("class ".length());
                classType = (Class) f.getGenericType();
            } else {
                log.trace("Abnormal className for " + f.getGenericType());
            }

            if (classType == null) {
                if ("int".equals(className)) {
                    return new Integer(fieldVal);
                } else if ("long".equals(className)) {
                    return new Long(fieldVal);
                } else if ("double".equals(className)) {
                    return new Double(fieldVal);
                } else if ("float".equals(className)) {
                    return new Float(fieldVal);
                } else if ("boolean".equals(className)) {
                    return new Boolean(fieldVal);
                } else if ("byte".equals(className)) {
                    return new Byte(fieldVal);
                } else if ("short".equals(className)) {
                    return new Short(fieldVal);
                }
            }

            // we have to explicitly create a new value object here because all we have is a string - won't know how to convert
            if (OpenmrsObject.class.isAssignableFrom(classType)) {
                o = getOpenmrsObj(className, fieldVal);
            } else if ("java.lang.Integer".equals(className) && !("integer".equals(nodeDefinedClassName)
                    || "java.lang.Integer".equals(nodeDefinedClassName))) {
                // if we're dealing with a field like PersonAttributeType.foreignKey, the actual value was changed from
                // an integer to a uuid by the HibernateSyncInterceptor.  The nodeDefinedClassName is the node.type which is the 
                // actual classname as defined by the PersonAttributeType.format.  However, the field.getClassName is 
                // still an integer because thats what the db stores.  we need to convert the uuid to the pk integer and return it
                OpenmrsObject obj = getOpenmrsObj(nodeDefinedClassName, fieldVal);
                o = obj.getId();
            } else if ("java.lang.String".equals(className) && !("text".equals(nodeDefinedClassName)
                    || "string".equals(nodeDefinedClassName) || "java.lang.String".equals(nodeDefinedClassName)
                    || "integer".equals(nodeDefinedClassName)
                    || "java.lang.Integer".equals(nodeDefinedClassName) || fieldVal.isEmpty())) {
                // if we're dealing with a field like PersonAttribute.value, the actual value was changed from
                // a string to a uuid by the HibernateSyncInterceptor.  The nodeDefinedClassName is the node.type which is the 
                // actual classname as defined by the PersonAttributeType.format.  However, the field.getClassName is 
                // still String because thats what the db stores.  we need to convert the uuid to the pk integer/string and return it
                OpenmrsObject obj = getOpenmrsObj(nodeDefinedClassName, fieldVal);
                if (obj == null) {
                    if (StringUtils.hasText(fieldVal)) {
                        // If we make it here, and we are dealing with person attribute values, then just return the string value as-is
                        if (PersonAttribute.class.isAssignableFrom(f.getDeclaringClass())
                                && "value".equals(f.getName())) {
                            o = fieldVal;
                        } else {
                            // throw a warning if we're having trouble converting what should be a valid value
                            log.error("Unable to convert value '" + fieldVal + "' into a "
                                    + nodeDefinedClassName);
                            throw new SyncException("Unable to convert value '" + fieldVal + "' into a "
                                    + nodeDefinedClassName);
                        }
                    } else {
                        // if fieldVal is empty, just save an empty string here too
                        o = "";
                    }
                } else {
                    o = obj.getId().toString(); // call toString so the class types match when looking up the setter
                }
            } else if (Collection.class.isAssignableFrom(classType)) {
                // this is a collection of items. this is intentionally not in the convertStringToObject method

                Collection tmpCollection = null;
                if (Set.class.isAssignableFrom(classType))
                    tmpCollection = new LinkedHashSet();
                else
                    tmpCollection = new Vector();

                // get the type of class held in the collection
                String collectionTypeClassName = null;
                java.lang.reflect.Type collectionType = ((java.lang.reflect.ParameterizedType) f
                        .getGenericType()).getActualTypeArguments()[0];
                if (collectionType.toString().startsWith("class "))
                    collectionTypeClassName = collectionType.toString().substring("class ".length());

                // get the type of class defined in the text node
                // if it is different, we could be dealing with something like Cohort.memberIds
                // node type comes through as java.util.Set<classname>
                String nodeDefinedCollectionType = null;
                int indexOfLT = nodeDefinedClassName.indexOf("<");
                if (indexOfLT > 0)
                    nodeDefinedCollectionType = nodeDefinedClassName.substring(indexOfLT + 1,
                            nodeDefinedClassName.length() - 1);

                // change the string to just a comma delimited list
                fieldVal = fieldVal.replaceFirst("\\[", "").replaceFirst("\\]", "");

                for (String eachFieldVal : fieldVal.split(",")) {
                    eachFieldVal = eachFieldVal.trim(); // take out whitespace
                    if (!StringUtils.hasText(eachFieldVal))
                        continue;
                    // try to convert to a simple object
                    Object tmpObject = convertStringToObject(eachFieldVal, (Class) collectionType);

                    // convert to an openmrs object
                    if (tmpObject == null && nodeDefinedCollectionType != null)
                        tmpObject = getOpenmrsObj(nodeDefinedCollectionType, eachFieldVal).getId();

                    if (tmpObject == null)
                        log.error("Unable to convert: " + eachFieldVal + " to a " + collectionTypeClassName);
                    else
                        tmpCollection.add(tmpObject);
                }

                o = tmpCollection;
            } else if (Map.class.isAssignableFrom(classType) || Properties.class.isAssignableFrom(classType)) {
                Object tmpMap = SyncUtil.getNormalizer(classType).fromString(classType, fieldVal);

                //if we were able to convert and got anything at all back, assign it
                if (tmpMap != null) {
                    o = tmpMap;
                }
            } else if ((o = convertStringToObject(fieldVal, classType)) != null) {
                log.trace("Converted " + fieldVal + " into " + classType.getName());
            } else {
                log.debug("Don't know how to deserialize class: " + className);
            }
        }
    }

    if (o == null)
        log.debug("Never found a property named: " + fieldName + " for this class");

    return o;
}

From source file:org.apache.openjpa.enhance.PCEnhancer.java

/**
 * Helper method to return the declaring PersistenceCapable class of
 * the given field.//from w  w  w . ja  v  a 2 s.c  o  m
 *
 * @param fieldName the name of the field
 * @param owner the nominal owner of the field
 * @return the metadata for the PersistenceCapable type that
 * declares the field (and therefore has the static method), or null if none
 */
private ClassMetaData getPersistenceCapableOwner(String fieldName, Class owner) {
    // find the actual ancestor class that declares the field, then
    // check if the class is persistent, and if the field is managed
    Field f = Reflection.findField(owner, fieldName, false);
    if (f == null)
        return null;

    // managed interface
    if (_meta != null && _meta.getDescribedType().isInterface())
        return _meta;

    return _repos.getMetaData(f.getDeclaringClass(), null, false);
}

From source file:org.apache.openjpa.enhance.PCEnhancer.java

/**
 * Add the fields to hold detached state and their accessor methods.
 *
 * @param impl whether to fully implement detach state functionality
 *//*ww  w  . j  a va2  s. c om*/
private void addDetachedStateMethods(boolean impl) {
    Field detachField = _meta.getDetachedStateField();
    String name = null;
    String declarer = null;
    if (impl && detachField == null) {
        name = PRE + "DetachedState";
        declarer = _pc.getName();
        BCField field = _pc.declareField(name, Object.class);
        field.makePrivate();
        field.setTransient(true);
    } else if (impl) {
        name = detachField.getName();
        declarer = detachField.getDeclaringClass().getName();
    }

    // public Object pcGetDetachedState ()
    BCMethod method = _pc.declareMethod(PRE + "GetDetachedState", Object.class, null);
    method.setStatic(false);
    method.makePublic();
    int access = method.getAccessFlags();

    Code code = method.getCode(true);
    if (impl) {
        // return pcDetachedState;
        loadManagedInstance(code, false);
        getfield(code, _managedType.getProject().loadClass(declarer), name);
    } else
        code.constant().setNull();
    code.areturn();
    code.calculateMaxLocals();
    code.calculateMaxStack();

    // public void pcSetDetachedState (Object state)
    method = _pc.declareMethod(PRE + "SetDetachedState", void.class, new Class[] { Object.class });
    method.setAccessFlags(access);
    code = method.getCode(true);
    if (impl) {
        // pcDetachedState = state;
        loadManagedInstance(code, false);
        code.aload().setParam(0);
        putfield(code, _managedType.getProject().loadClass(declarer), name, Object.class);
    }
    code.vreturn();
    code.calculateMaxStack();
    code.calculateMaxLocals();
}

From source file:adalid.core.AbstractEntity.java

@SuppressWarnings("deprecation")
private void annotateEntityParentProperty(Class<?> type) {
    Class<?> annotatedClass = XS1.getAnnotatedClass(type, EntityParentProperty.class);
    if (annotatedClass != null) {
        EntityParentProperty annotation = annotatedClass.getAnnotation(EntityParentProperty.class);
        if (annotation != null) {
            _parentFieldName = annotation.value();
            if (StringUtils.isBlank(_parentFieldName)) {
                _parentFieldName = null;
            } else {
                Field field = getParentField(_parentFieldName, Entity.class);
                _parentField = field == null ? null
                        : getParentField(_parentFieldName, field.getDeclaringClass());
                _annotatedWithEntityParentProperty = _parentField != null;
            }//from  w  w  w .j  av  a2s . c  o m
        }
    }
}

From source file:adalid.core.AbstractEntity.java

void setParentField() {
    Field field = getAnnotations().get(ParentProperty.class);
    if (field != null) {
        String fieldName = field.getName();
        if (field.equals(getParentField(fieldName, field.getDeclaringClass()))) {
            _parentFieldName = fieldName;
            _parentField = field;//w ww .j  a va2  s .  c o m
        }
    }
}

From source file:adalid.core.AbstractEntity.java

public void linkForeignSegmentProperty(Entity foreignSegmentProperty) {
    //      if (isParameter() || isParameterProperty()) {
    //          return;
    //      }/*from   w  w w.j a  va2 s  .  co  m*/
    String message = "failed to link foreign segment property of " + getFullName();
    if (foreignSegmentProperty == null) {
        message += "; supplied foreign property is null";
        logger.error(message);
        TLC.getProject().getParser().increaseErrorCount();
    } else {
        Field field = foreignSegmentProperty.getDeclaringField();
        boolean aye = field.isAnnotationPresent(SegmentProperty.class);
        if (aye) {
            _segmentProperty = foreignSegmentProperty;
        } else {
            message += "; " + field.getDeclaringClass().getSimpleName() + "." + field.getName()
                    + " is not a segment property";
            logger.error(message);
            TLC.getProject().getParser().increaseErrorCount();
        }
    }
}

From source file:adalid.core.AbstractEntity.java

public void linkForeignOwnerProperty(Entity foreignOwnerProperty) {
    //      if (isParameter() || isParameterProperty()) {
    //          return;
    //      }/*w w w  .java 2 s.  c  o  m*/
    String message = "failed to link foreign owner property of " + getFullName();
    if (foreignOwnerProperty == null) {
        message += "; supplied foreign property is null";
        logger.error(message);
        TLC.getProject().getParser().increaseErrorCount();
    } else {
        Class<?> foreignOwnerPropertyClass = foreignOwnerProperty.getClass();
        Class<? extends Entity> userEntityClass = TLC.getProject().getUserEntityClass();
        if (userEntityClass != null && userEntityClass.isAssignableFrom(foreignOwnerPropertyClass)) {
            Field field = foreignOwnerProperty.getDeclaringField();
            boolean aye = field.isAnnotationPresent(OwnerProperty.class);
            if (aye) {
                _ownerProperty = foreignOwnerProperty;
            } else {
                message += "; " + field.getDeclaringClass().getSimpleName() + "." + field.getName()
                        + " is not an owner property";
                logger.error(message);
                TLC.getProject().getParser().increaseErrorCount();
            }
        } else {
            message += "; " + userEntityClass + " is not assignable from " + foreignOwnerPropertyClass;
            logger.error(message);
            TLC.getProject().getParser().increaseErrorCount();
        }
    }
}

From source file:org.diorite.cfg.system.ConfigField.java

/**
 * Construct new config field for given {@link Field}.
 *
 * @param field source field./*from  w w w .jav a  2s  .  com*/
 * @param index index of field in class. Used to set priority of field.
 */
public ConfigField(final Field field, final int index) {
    this.field = field;
    {
        getAllPossibleTypes(field).forEach(TemplateCreator::checkTemplate);
    }
    this.index = index;

    final String[] comments = TemplateCreator.readComments(field);
    this.header = comments[0];
    this.footer = comments[1];
    {
        final CfgName annotation = field.getAnnotation(CfgName.class);
        this.name = (annotation != null) ? annotation.value() : field.getName();
    }
    {
        final CfgPriority annotation = field.getAnnotation(CfgPriority.class);
        this.priority = (annotation != null) ? (annotation.value() * -1) : index;
    }

    for (final FieldOptions option : FieldOptions.values()) {
        if (!option.contains(field)) {
            continue;
        }
        this.options.put(option, option.get(this, field));
    }

    final Class<?> type = DioriteReflectionUtils.getPrimitive(field.getType());
    Supplier<Object> def = null;
    annotation: {
        {
            final CfgBooleanDefault annotation = field.getAnnotation(CfgBooleanDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgBooleanArrayDefault annotation = field.getAnnotation(CfgBooleanArrayDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgByteDefault annotation = field.getAnnotation(CfgByteDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgShortDefault annotation = field.getAnnotation(CfgShortDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgIntDefault annotation = field.getAnnotation(CfgIntDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgLongDefault annotation = field.getAnnotation(CfgLongDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgFloatDefault annotation = field.getAnnotation(CfgFloatDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgDoubleDefault annotation = field.getAnnotation(CfgDoubleDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }

        {
            final CfgByteArrayDefault annotation = field.getAnnotation(CfgByteArrayDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgCharDefault annotation = field.getAnnotation(CfgCharDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgCharArrayDefault annotation = field.getAnnotation(CfgCharArrayDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgShortArrayDefault annotation = field.getAnnotation(CfgShortArrayDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgIntArrayDefault annotation = field.getAnnotation(CfgIntArrayDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgLongArrayDefault annotation = field.getAnnotation(CfgLongArrayDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgFloatArrayDefault annotation = field.getAnnotation(CfgFloatArrayDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgDoubleArrayDefault annotation = field.getAnnotation(CfgDoubleArrayDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgStringDefault annotation = field.getAnnotation(CfgStringDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }
        {
            final CfgStringArrayDefault annotation = field.getAnnotation(CfgStringArrayDefault.class);
            if (annotation != null) {
                def = annotation::value;
                break annotation;
            }
        }

        if (type.isEnum()) {
            for (final Annotation a : field.getAnnotations()) {
                if (a.annotationType().isAnnotationPresent(CfgCustomDefault.class)) {
                    final Annotation annotation = field.getAnnotation(a.annotationType());
                    this.invoker = DioriteReflectionUtils.getMethod(annotation.getClass(), "value");
                    def = () -> this.invoker.invoke(annotation);
                    break annotation;
                }
            }
        }
    }
    final CfgDelegateDefault annotation = field.getAnnotation(CfgDelegateDefault.class);
    if (annotation != null) {
        final String path = annotation.value();
        final Supplier<Object> basicDelegate = getBasicDelegate(path);
        if (basicDelegate != null) {
            def = basicDelegate;
        } else if (path.equalsIgnoreCase("{new}")) {
            final ConstructorInvoker constructor = DioriteReflectionUtils.getConstructor(field.getType());
            def = constructor::invoke;
        } else {
            final int sepIndex = path.indexOf("::");
            final Class<?> clazz;
            final String methodName;
            if (sepIndex == -1) {
                clazz = field.getDeclaringClass();
                methodName = path;
            } else {
                try {
                    Class<?> tmpClass = DioriteReflectionUtils
                            .tryGetCanonicalClass(path.substring(0, sepIndex));
                    if (tmpClass == null) {
                        tmpClass = DioriteReflectionUtils
                                .tryGetCanonicalClass(field.getDeclaringClass().getPackage().getName() + "."
                                        + path.substring(0, sepIndex));
                        if (tmpClass == null) {
                            tmpClass = DioriteReflectionUtils.getNestedClass(field.getDeclaringClass(),
                                    path.substring(0, sepIndex));
                        }
                    }
                    clazz = tmpClass;
                } catch (final Exception e) {
                    throw new RuntimeException("Can't find class for: " + path, e);
                }
                methodName = path.substring(sepIndex + 2);
            }
            if (clazz == null) {
                throw new RuntimeException("Can't find class for delegate: " + path);
            }
            final MethodInvoker methodInvoker = DioriteReflectionUtils.getMethod(clazz, methodName, false);
            if (methodInvoker == null) {
                final ReflectGetter<Object> reflectGetter = DioriteReflectionUtils.getReflectGetter(methodName,
                        clazz);
                def = () -> reflectGetter.get(null);
            } else {
                def = () -> methodInvoker.invoke(null);
            }
        }
    }
    this.def = def;
}