Example usage for java.lang.reflect Field getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the field represented by this Field object.

Usage

From source file:com.yahoo.egads.data.JsonEncoder.java

public static void // modifies json_out
        toJson(Object object, JSONStringer json_out) throws Exception {
    json_out.object();//from   w ww  . j  a  va  2s. c  om
    // for each inherited class...
    for (Class c = object.getClass(); c != Object.class; c = c.getSuperclass()) {
        // for each member variable... 
        Field[] fields = c.getDeclaredFields();
        for (Field f : fields) {
            // if variable is static/private... skip it
            if (Modifier.isStatic(f.getModifiers())) {
                continue;
            }
            if (Modifier.isPrivate(f.getModifiers())) {
                continue;
            }
            Object value = f.get(object);

            // if variable is a complex type... recurse on sub-objects
            if (value instanceof JsonAble) {
                json_out.key(f.getName());
                ((JsonAble) value).toJson(json_out);
                // if variable is an array... recurse on sub-objects
            } else if (value instanceof ArrayList) {
                json_out.key(f.getName());
                json_out.array();
                for (Object e : (ArrayList) value) {
                    toJson(e, json_out);
                }
                json_out.endArray();
                // if variable is a simple type... convert to json
            } else {
                json_out.key(f.getName()).value(value);
            }
        }
    }
    json_out.endObject();
}

From source file:org.appverse.web.framework.backend.api.converters.helpers.ConverterUtils.java

/**
 * Copy source bean single properties to target bean
 * //from  ww  w .j a  v a 2s .com
 * @param source
 *            Source Bean
 * @param target
 *            Target Bean
 * @param sourceFields
 *            Fields of source Bean
 * @throws Exception
 */
private static void copyPlainFields(AbstractBean source, AbstractBean target, Field[] sourceFields)
        throws Exception {
    String[] ignoreProperties = new String[0];

    // For each source field...
    for (Field field : sourceFields) {
        // If source field is a bean...
        if (AbstractBean.class.isAssignableFrom(field.getType())) {
            // Put it in ignore properties
            ignoreProperties = (String[]) ArrayUtils.add(ignoreProperties, field.getName());
        }
    }

    // Copy properties with Spring Framework copy properties
    org.springframework.beans.BeanUtils.copyProperties(source, target, ignoreProperties);
}

From source file:cn.xdf.thinkutils.db2.util.sql.UpdateSqlBuilder.java

/**
 * ,?/*from w ww  .  j  a va 2 s . c om*/
 * 
 * @return
 * @throws DBException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
public static ArrayListEx getFieldsAndValue(Object entity)
        throws DBException, IllegalArgumentException, IllegalAccessException {
    // TODO Auto-generated method stub
    ArrayListEx arrayList = new ArrayListEx();
    if (entity == null) {
        throw new DBException("?");
    }
    Class<?> clazz = entity.getClass();
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {

        if (!DBUtils.isTransient(field)) {
            if (DBUtils.isBaseDateType(field)) {
                PrimaryKey annotation = field.getAnnotation(PrimaryKey.class);
                if (annotation == null || !annotation.autoIncrement()) {
                    String columnName = DBUtils.getColumnByField(field);
                    field.setAccessible(true);
                    arrayList.add((columnName != null && !columnName.equals("")) ? columnName : field.getName(),
                            field.get(entity) == null ? null : field.get(entity).toString());
                }
            }
        }
    }
    return arrayList;
}

From source file:com.unboundid.scim2.common.utils.SchemaUtils.java

/**
 * This method will find a java Field for with a particular name.  If
 * needed, this method will search through super classes.  The field
 * does not need to be public.//  ww  w  .ja v a 2s.c  o  m
 *
 * @param cls the java Class to search.
 * @param fieldName the name of the field to find.
 * @return the java field.
 */
public static Field findField(final Class<?> cls, final String fieldName) {
    Class<?> currentClass = cls;
    while (currentClass != null) {
        Field[] fields = currentClass.getDeclaredFields();
        for (Field field : fields) {
            if (field.getName().equals(fieldName)) {
                return field;
            }
        }
        currentClass = currentClass.getSuperclass();
    }

    return null;
}

From source file:ch.rasc.extclassgenerator.association.AbstractAssociation.java

public static AbstractAssociation createAssociation(ModelAssociation associationAnnotation, ModelBean model,
        Class<?> typeOfFieldOrReturnValue, Class<?> declaringClass, String name) {
    ModelAssociationType type = associationAnnotation.value();

    Class<?> associationClass = associationAnnotation.model();
    if (associationClass == Object.class) {
        associationClass = typeOfFieldOrReturnValue;
    }//w w  w .  j  a v a2 s. c  om

    final AbstractAssociation association;

    if (type == ModelAssociationType.HAS_MANY) {
        association = new HasManyAssociation(associationClass);
    } else if (type == ModelAssociationType.BELONGS_TO) {
        association = new BelongsToAssociation(associationClass);
    } else {
        association = new HasOneAssociation(associationClass);
    }

    association.setAssociationKey(name);

    if (StringUtils.hasText(associationAnnotation.foreignKey())) {
        association.setForeignKey(associationAnnotation.foreignKey());
    } else if (type == ModelAssociationType.HAS_MANY) {
        association.setForeignKey(StringUtils.uncapitalize(declaringClass.getSimpleName()) + "_id");
    } else if (type == ModelAssociationType.BELONGS_TO || type == ModelAssociationType.HAS_ONE) {
        association.setForeignKey(name + "_id");
    }

    if (StringUtils.hasText(associationAnnotation.primaryKey())) {
        association.setPrimaryKey(associationAnnotation.primaryKey());
    } else if (type == ModelAssociationType.HAS_MANY && StringUtils.hasText(model.getIdProperty())
            && !model.getIdProperty().equals("id")) {
        association.setPrimaryKey(model.getIdProperty());
    } else if (type == ModelAssociationType.BELONGS_TO || type == ModelAssociationType.HAS_ONE) {
        Model associationModelAnnotation = associationClass.getAnnotation(Model.class);
        if (associationModelAnnotation != null && StringUtils.hasText(associationModelAnnotation.idProperty())
                && !associationModelAnnotation.idProperty().equals("id")) {
            association.setPrimaryKey(associationModelAnnotation.idProperty());
        }
        ReflectionUtils.doWithFields(associationClass, new FieldCallback() {

            @Override
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                if (field.getAnnotation(ModelId.class) != null && !"id".equals(field.getName())) {
                    association.setPrimaryKey(field.getName());
                }
            }

        });
    }

    if (type == ModelAssociationType.HAS_MANY) {
        HasManyAssociation hasManyAssociation = (HasManyAssociation) association;

        if (StringUtils.hasText(associationAnnotation.setterName())) {
            LogFactory.getLog(ModelGenerator.class)
                    .warn(getWarningText(declaringClass, name, association.getType(), "setterName"));
        }

        if (StringUtils.hasText(associationAnnotation.getterName())) {
            LogFactory.getLog(ModelGenerator.class)
                    .warn(getWarningText(declaringClass, name, association.getType(), "getterName"));
        }

        if (associationAnnotation.autoLoad()) {
            hasManyAssociation.setAutoLoad(Boolean.TRUE);
        }
        if (StringUtils.hasText(associationAnnotation.name())) {
            hasManyAssociation.setName(associationAnnotation.name());
        } else {
            hasManyAssociation.setName(name);
        }

    } else if (type == ModelAssociationType.BELONGS_TO) {
        BelongsToAssociation belongsToAssociation = (BelongsToAssociation) association;

        if (StringUtils.hasText(associationAnnotation.setterName())) {
            belongsToAssociation.setSetterName(associationAnnotation.setterName());
        } else {
            belongsToAssociation.setSetterName("set" + StringUtils.capitalize(name));
        }

        if (StringUtils.hasText(associationAnnotation.getterName())) {
            belongsToAssociation.setGetterName(associationAnnotation.getterName());
        } else {
            belongsToAssociation.setGetterName("get" + StringUtils.capitalize(name));
        }

        if (associationAnnotation.autoLoad()) {
            LogFactory.getLog(ModelGenerator.class)
                    .warn(getWarningText(declaringClass, name, association.getType(), "autoLoad"));
        }
        if (StringUtils.hasText(associationAnnotation.name())) {
            LogFactory.getLog(ModelGenerator.class)
                    .warn(getWarningText(declaringClass, name, association.getType(), "name"));
        }
    } else {
        HasOneAssociation hasOneAssociation = (HasOneAssociation) association;

        if (StringUtils.hasText(associationAnnotation.setterName())) {
            hasOneAssociation.setSetterName(associationAnnotation.setterName());
        } else {
            hasOneAssociation.setSetterName("set" + StringUtils.capitalize(name));
        }

        if (StringUtils.hasText(associationAnnotation.getterName())) {
            hasOneAssociation.setGetterName(associationAnnotation.getterName());
        } else {
            hasOneAssociation.setGetterName("get" + StringUtils.capitalize(name));
        }

        if (associationAnnotation.autoLoad()) {
            LogFactory.getLog(ModelGenerator.class)
                    .warn(getWarningText(declaringClass, name, association.getType(), "autoLoad"));
        }

        if (StringUtils.hasText(associationAnnotation.name())) {
            hasOneAssociation.setName(associationAnnotation.name());
        }
    }

    if (StringUtils.hasText(associationAnnotation.instanceName())) {
        association.setInstanceName(associationAnnotation.instanceName());
    }

    return association;
}

From source file:cn.xdf.thinkutils.db2.util.sql.InsertSqlBuilder.java

/**
 * ,?//from  w w  w .  j  a  v  a  2 s .  co  m
 * 
 * @return
 * @throws DBException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
public static ArrayListEx getFieldsAndValue(Object entity)
        throws DBException, IllegalArgumentException, IllegalAccessException {
    // TODO Auto-generated method stub
    ArrayListEx arrayList = new ArrayListEx();
    if (entity == null) {
        throw new DBException("?");
    }
    Class<?> clazz = entity.getClass();
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {

        if (!DBUtils.isTransient(field)) {
            if (DBUtils.isBaseDateType(field)) {
                PrimaryKey annotation = field.getAnnotation(PrimaryKey.class);
                if (annotation != null && annotation.autoIncrement()) {

                } else {
                    String columnName = DBUtils.getColumnByField(field);
                    field.setAccessible(true);
                    arrayList.add((columnName != null && !columnName.equals("")) ? columnName : field.getName(),
                            field.get(entity) == null ? null : field.get(entity).toString());
                }

            }
        }
    }
    return arrayList;
}

From source file:com.sugaronrest.restapicalls.ModuleInfo.java

/**
 * Gets json names from module fields annotations.
 *
 * @param type The Java module type./*ww w .  j  a va2 s. co  m*/
 * @return List of json property names.
 */
private static List<ModuleProperty> getFieldAnnotations(Class type) {
    List<ModuleProperty> modelProperties = new ArrayList<ModuleProperty>();
    Iterable<Field> fields = getFieldsUpTo(type, Object.class);
    for (Field field : fields) {
        Annotation[] annotations = field.getAnnotations();

        for (Annotation annotation : annotations) {
            if (annotation instanceof JsonProperty) {
                JsonProperty property = (JsonProperty) annotation;
                ModuleProperty moduleProperty = new ModuleProperty();
                moduleProperty.name = field.getName();
                moduleProperty.jsonName = property.value();
                moduleProperty.type = field.getType();
                moduleProperty.isNumeric = isTypeNumeric(field.getType());
                modelProperties.add(moduleProperty);
            }
        }
    }

    return modelProperties;
}

From source file:de.escalon.hypermedia.spring.uber.UberUtils.java

/**
 * Recursively converts object to nodes of uber data.
 *
 * @param objectNode//from   w w  w .  j  a v  a  2s.  c o  m
 *         to append to
 * @param object
 *         to convert
 */
public static void toUberData(AbstractUberNode objectNode, Object object) {
    Set<String> filtered = FILTER_RESOURCE_SUPPORT;
    if (object == null) {
        return;
    }

    try {
        // TODO: move all returns to else branch of property descriptor handling
        if (object instanceof Resource) {
            Resource<?> resource = (Resource<?>) object;
            objectNode.addLinks(resource.getLinks());
            toUberData(objectNode, resource.getContent());
            return;
        } else if (object instanceof Resources) {
            Resources<?> resources = (Resources<?>) object;

            // TODO set name using EVO see HypermediaSupportBeanDefinitionRegistrar

            objectNode.addLinks(resources.getLinks());

            Collection<?> content = resources.getContent();
            toUberData(objectNode, content);
            return;
        } else if (object instanceof ResourceSupport) {
            ResourceSupport resource = (ResourceSupport) object;

            objectNode.addLinks(resource.getLinks());

            // wrap object attributes below to avoid endless loop

        } else if (object instanceof Collection) {
            Collection<?> collection = (Collection<?>) object;
            for (Object item : collection) {
                // TODO name must be repeated for each collection item
                UberNode itemNode = new UberNode();
                objectNode.addData(itemNode);
                toUberData(itemNode, item);
            }
            return;
        }
        if (object instanceof Map) {
            Map<?, ?> map = (Map<?, ?>) object;
            for (Entry<?, ?> entry : map.entrySet()) {
                String key = entry.getKey().toString();
                Object content = entry.getValue();
                Object value = getContentAsScalarValue(content);
                UberNode entryNode = new UberNode();
                objectNode.addData(entryNode);
                entryNode.setName(key);
                if (value != null) {
                    entryNode.setValue(value);
                } else {
                    toUberData(entryNode, content);
                }
            }
        } else {
            Map<String, PropertyDescriptor> propertyDescriptors = PropertyUtils.getPropertyDescriptors(object);
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors.values()) {
                String name = propertyDescriptor.getName();
                if (filtered.contains(name)) {
                    continue;
                }
                UberNode propertyNode = new UberNode();
                Object content = propertyDescriptor.getReadMethod().invoke(object);

                if (isEmptyCollectionOrMap(content, propertyDescriptor.getPropertyType())) {
                    continue;
                }

                Object value = getContentAsScalarValue(content);
                propertyNode.setName(name);
                objectNode.addData(propertyNode);
                if (value != null) {
                    // for each scalar property of a simple bean, add valuepair nodes to data
                    propertyNode.setValue(value);
                } else {
                    toUberData(propertyNode, content);
                }
            }

            Field[] fields = object.getClass().getFields();
            for (Field field : fields) {
                String name = field.getName();
                if (!propertyDescriptors.containsKey(name)) {
                    Object content = field.get(object);
                    Class<?> type = field.getType();
                    if (isEmptyCollectionOrMap(content, type)) {
                        continue;
                    }
                    UberNode propertyNode = new UberNode();

                    Object value = getContentAsScalarValue(content);
                    propertyNode.setName(name);
                    objectNode.addData(propertyNode);
                    if (value != null) {
                        // for each scalar property of a simple bean, add valuepair nodes to data
                        propertyNode.setValue(value);
                    } else {
                        toUberData(propertyNode, content);
                    }

                }
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException("failed to transform object " + object, ex);
    }
}

From source file:com.erudika.para.core.ParaObjectUtils.java

/**
 * Converts a map of fields/values to a domain object. Only annotated fields are populated. This method forms the
 * basis of an Object/Grid Mapper./*from   w  ww .  jav  a2  s .  co m*/
 * <br>
 * Map values that are JSON objects are converted to their corresponding Java types. Nulls and primitive types are
 * preserved.
 *
 * @param <P> the object type
 * @param pojo the object to populate with data
 * @param data the map of fields/values
 * @param filter a filter annotation. fields that have it will be skipped
 * @return the populated object
 */
public static <P extends ParaObject> P setAnnotatedFields(P pojo, Map<String, Object> data,
        Class<? extends Annotation> filter) {
    if (data == null || data.isEmpty()) {
        return null;
    }
    try {
        if (pojo == null) {
            // try to find a declared class in the core package
            pojo = (P) toClass((String) data.get(Config._TYPE)).getConstructor().newInstance();
        }
        List<Field> fields = getAllDeclaredFields(pojo.getClass());
        Map<String, Object> props = new HashMap<String, Object>(data);
        for (Field field : fields) {
            boolean dontSkip = ((filter == null) ? true : !field.isAnnotationPresent(filter));
            String name = field.getName();
            Object value = data.get(name);
            if (field.isAnnotationPresent(Stored.class) && dontSkip) {
                // try to read a default value from the bean if any
                if (value == null && PropertyUtils.isReadable(pojo, name)) {
                    value = PropertyUtils.getProperty(pojo, name);
                }
                // handle complex JSON objects deserialized to Maps, Arrays, etc.
                if (!Utils.isBasicType(field.getType()) && value instanceof String) {
                    // in this case the object is a flattened JSON string coming from the DB
                    value = getJsonReader(field.getType()).readValue(value.toString());
                }
                field.setAccessible(true);
                BeanUtils.setProperty(pojo, name, value);
            }
            props.remove(name);
        }
        // handle unknown (user-defined) fields
        if (!props.isEmpty() && pojo instanceof Sysprop) {
            for (Map.Entry<String, Object> entry : props.entrySet()) {
                String name = entry.getKey();
                Object value = entry.getValue();
                // handle the case where we have custom user-defined properties
                // which are not defined as Java class fields
                if (!PropertyUtils.isReadable(pojo, name)) {
                    if (value == null) {
                        ((Sysprop) pojo).removeProperty(name);
                    } else {
                        ((Sysprop) pojo).addProperty(name, value);
                    }
                }
            }
        }
    } catch (Exception ex) {
        logger.error(null, ex);
        pojo = null;
    }
    return pojo;
}

From source file:ea.compoment.db.util.sql.UpdateSqlBuilder.java

/**
 * ,?//from  w w  w  . j  a  va  2s.  c o  m
 * 
 * @return
 * @throws DBException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
public static NVArrayList getFieldsAndValue(Object entity)
        throws DBException, IllegalArgumentException, IllegalAccessException {
    NVArrayList arrayList = new NVArrayList();
    if (entity == null) {
        throw new DBException("?");
    }
    Class<?> clazz = entity.getClass();
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {

        if (!DBAnnoUtils.isTransient(field)) {
            if (DBAnnoUtils.isBaseDateType(field)) {
                PrimaryKey annotation = field.getAnnotation(PrimaryKey.class);
                if (annotation == null || !annotation.autoIncrement()) {
                    String columnName = DBAnnoUtils.getColumnByField(field);
                    field.setAccessible(true);
                    arrayList.add((columnName != null && !columnName.equals("")) ? columnName : field.getName(),
                            field.get(entity) == null ? null : field.get(entity).toString());
                }
            }
        }
    }
    return arrayList;
}