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.searchbox.core.ref.ReflectionUtils.java

public static void copyAllFields(Object from, Object to) {
    for (Field fromField : findAllFields(from.getClass())) {
        try {//  w w w. j av a  2  s  .c om
            Field toField = findUnderlying(to.getClass(), fromField.getName());
            if (toField != null) {
                toField.setAccessible(true);
                fromField.setAccessible(true);
                toField.set(to, fromField.get(from));
            }
        } catch (Exception e) {
            LOGGER.warn("Could not copye Fields.", e);
        }
    }
}

From source file:com.qumoon.commons.BeanMapper.java

public static <T extends com.google.protobuf.GeneratedMessage> T convertBean2Proto(
        com.google.protobuf.GeneratedMessage.Builder message, Object srcObject) throws Exception {
    for (Field srcField : srcObject.getClass().getDeclaredFields()) {
        Object value = PropertyUtils.getProperty(srcObject, srcField.getName());
        if (value == null) {
            continue;
        }//from   w  w w. j  a v a2 s . com
        Descriptors.FieldDescriptor fd = message.getDescriptorForType().findFieldByName(srcField.getName());
        if (null == fd) {
            continue;
        }
        if (srcField.getType() == BigDecimal.class) {
            message.setField(fd, ((BigDecimal) value).toString());
            continue;
        } else {
            if (srcField.getType() == Date.class) {
                message.setField(fd, ((Date) value).getTime());
                continue;
            } else {
                message.setField(fd, value);
            }
        }
    }
    return (T) message.build();
}

From source file:com.hortonworks.streamline.storage.util.StorageUtils.java

public static List<Pair<Field, String>> getSearchableFieldValues(Storable storable)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    List<Pair<Field, String>> res = new ArrayList<>();
    for (Field field : storable.getClass().getDeclaredFields()) {
        if (field.getAnnotation(SearchableField.class) != null) {
            Object val = ReflectionHelper.invokeGetter(field.getName(), storable);
            if (val != null) {
                res.add(Pair.of(field, val instanceof String ? (String) val : val.toString()));
            }//  ww w .j  a va 2 s .com
        }
    }
    return res;
}

From source file:de.cosmocode.palava.salesforce.sync.NullFieldCollector.java

private static void collect(Set<String> nullFields, Object object) {
    LOG.trace("Collecting null fields on {}", object);
    final Field[] fields = object.getClass().getDeclaredFields();
    for (Field field : fields) {
        if (Modifier.isStatic(field.getModifiers()))
            continue;
        if ("fieldsToNull".equals(field.getName()))
            continue;
        try {/*from w  w w .  j a va2 s  . c o  m*/
            final boolean accessible = field.isAccessible();
            field.setAccessible(true);
            final Object value = field.get(object);
            field.setAccessible(accessible);
            if (value == null) {
                continue;
            } else if (value instanceof JAXBElement<?>) {
                final JAXBElement<?> jaxb = JAXBElement.class.cast(value);
                if (jaxb.getValue() == null) {
                    nullFields.add(nameOf(field));
                }
            }
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException(e);
        }
    }
    LOG.trace("Null fields on {}: {}", object, nullFields);
}

From source file:com.feilong.core.lang.reflect.FieldUtil.java

/**
 *  <code>obj</code> (<b>?</b>),key fieldName,value .
 * /*from   w ww .  j  a  v  a 2  s. c o m*/
 * <h3>:</h3>
 * 
 * <blockquote>
 * 
 * <pre class="code">
 * 
 * User user = new User(12L);
 * LOGGER.debug(JsonUtil.format(FieldUtil.getAllFieldNameAndValueMap(user, "date")));
 * 
 * </pre>
 * 
 * <b>:</b>
 * 
 * <pre class="code">
 * {
 * "age": null,
 * "id": 12
 * }
 * 
 * </pre>
 * 
 * </blockquote>
 *
 * @param obj
 *            the obj
 * @param excludeFieldNames
 *            ?field names,?nullOrEmpty ?
 * @return  <code>obj</code> null, {@link NullPointerException}<br>
 *          <code>fieldList</code> nullempty, {@link Collections#emptyMap()}<br>
 * @see #getAllFieldList(Class, String...)
 * @see #getFieldValue(Object, String)
 */
public static Map<String, Object> getAllFieldNameAndValueMap(Object obj, String... excludeFieldNames) {
    List<Field> fieldList = getAllFieldList(obj.getClass(), excludeFieldNames);
    if (isNullOrEmpty(fieldList)) {
        return Collections.emptyMap();
    }
    Map<String, Object> map = new TreeMap<String, Object>();
    for (Field field : fieldList) {
        map.put(field.getName(), getFieldValue(obj, field.getName()));
    }
    return map;
}

From source file:ReflectionHelper.java

public static Object getValue(Member member, Object object) {
    Object value = null;//from   ww  w.jav a 2s. c o  m

    if (member instanceof Method) {
        Method method = (Method) member;
        try {
            value = method.invoke(object);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Unable to access " + method.getName(), e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException("Unable to access " + method.getName(), e);
        }
    } else if (member instanceof Field) {
        Field field = (Field) member;
        try {
            value = field.get(object);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Unable to access " + field.getName(), e);
        }
    }
    return value;
}

From source file:com.hortonworks.registries.storage.util.StorageUtils.java

public static List<Pair<Field, Object>> getAnnotatedFieldValues(Storable storable,
        Class<? extends Annotation> clazz)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    List<Pair<Field, Object>> res = new ArrayList<>();
    for (Field field : storable.getClass().getDeclaredFields()) {
        if (field.getAnnotation(clazz) != null) {
            Object val = ReflectionHelper.invokeGetter(field.getName(), storable);
            if (val != null) {
                res.add(Pair.of(field, val));
            }/*from ww w.  j av  a2s.c om*/
        }
    }
    return res;
}

From source file:com.opencsv.bean.MappingUtils.java

/**
 * Determines which mapping strategy is appropriate for this bean.
 * The algorithm is:<ol>/*from   w w  w .  ja va  2 s .  c  o  m*/
 * <li>If annotations {@link CsvBindByPosition} or
 * {@link CsvCustomBindByPosition} are present,
 * {@link ColumnPositionMappingStrategy} is chosen.</li>
 * <li>Otherwise, {@link HeaderColumnNameMappingStrategy} is chosen. If
 * annotations are present, they will be used, otherwise the field names
 * will be used as the column names.</li></ol>
 * 
 * @param <T> The type of the bean for which the mapping strategy is sought
 * @param type The class of the bean for which the mapping strategy is sought
 * @return A functional mapping strategy for the bean in question
 */
public static <T> MappingStrategy<T> determineMappingStrategy(Class type) {
    // Check for annotations
    Field[] fields = FieldUtils.getAllFields(type);
    boolean positionAnnotationsPresent = false;
    for (Field field : fields) {
        if (field.isAnnotationPresent(CsvBindByPosition.class)
                || field.isAnnotationPresent(CsvCustomBindByPosition.class)) {
            positionAnnotationsPresent = true;
            break;
        }
        if (positionAnnotationsPresent) {
            break;
        }
    }

    // Set the mapping strategy according to what we've found.
    MappingStrategy<T> mappingStrategy;
    if (positionAnnotationsPresent) {
        ColumnPositionMappingStrategy<T> ms = new ColumnPositionMappingStrategy<T>();
        ms.setType(type);
        mappingStrategy = ms;
    } else {
        HeaderColumnNameMappingStrategy<T> ms = new HeaderColumnNameMappingStrategy<T>();
        ms.setType(type);

        // Ugly hack, but I have to get the field names into the stupid
        // strategy somehow.
        if (!ms.isAnnotationDriven()) {
            SortedSet<String> sortedFields = new TreeSet<String>();
            for (Field f : fields) {
                if (!f.isSynthetic()) { // Otherwise JaCoCo breaks tests
                    sortedFields.add(f.getName());
                }
            }
            String header = StringUtils.join(sortedFields, ',').concat("\n");
            try {
                ms.captureHeader(new CSVReader(new StringReader(header)));
                ms.findDescriptor(0);
            } catch (IOException e) {
                // Can't happen. It's a StringReader with a defined string.
            } catch (IntrospectionException e) {
                CsvBeanIntrospectionException csve = new CsvBeanIntrospectionException("");
                csve.initCause(e);
                throw csve;
            }
        }

        mappingStrategy = ms;
    }
    return mappingStrategy;
}

From source file:gr.abiss.calipso.jpasearch.json.serializer.FormSchemaSerializer.java

private static String getFormFieldConfig(Class domainClass, String fieldName) {
    String formSchemaJson = null;
    Field field = null;//w  w w  .j a va  2  s . c o m
    StringBuffer formConfig = new StringBuffer();
    String key = domainClass.getName() + "#" + fieldName;
    String cached = CONFIG_CACHE.get(key);
    if (StringUtils.isNotBlank(cached)) {
        formConfig.append(cached);
    } else {
        Class tmpClass = domainClass;
        do {
            for (Field tmpField : tmpClass.getDeclaredFields()) {
                String candidateName = tmpField.getName();
                if (candidateName.equals(fieldName)) {
                    field = tmpField;
                    FormSchemas formSchemasAnnotation = null;
                    if (field.isAnnotationPresent(FormSchemas.class)) {
                        formSchemasAnnotation = field.getAnnotation(FormSchemas.class);
                        gr.abiss.calipso.jpasearch.annotation.FormSchemaEntry[] formSchemas = formSchemasAnnotation
                                .value();
                        LOGGER.info("getFormFieldConfig, formSchemas: " + formSchemas);
                        if (formSchemas != null) {
                            for (int i = 0; i < formSchemas.length; i++) {
                                if (i > 0) {
                                    formConfig.append(comma);
                                }
                                gr.abiss.calipso.jpasearch.annotation.FormSchemaEntry formSchemaAnnotation = formSchemas[i];
                                LOGGER.info(
                                        "getFormFieldConfig, formSchemaAnnotation: " + formSchemaAnnotation);
                                appendFormFieldSchema(formConfig, formSchemaAnnotation.state(),
                                        formSchemaAnnotation.json());
                            }
                        }
                        //formConfig = formSchemasAnnotation.json();
                    } else {
                        appendFormFieldSchema(formConfig,
                                gr.abiss.calipso.jpasearch.annotation.FormSchemaEntry.STATE_DEFAULT,
                                gr.abiss.calipso.jpasearch.annotation.FormSchemaEntry.TYPE_STRING);
                    }
                    break;
                }
            }
            tmpClass = tmpClass.getSuperclass();
        } while (tmpClass != null && field == null);
        formSchemaJson = formConfig.toString();
        CONFIG_CACHE.put(key, formSchemaJson);
    }

    return formSchemaJson;
}

From source file:de.cosmocode.palava.salesforce.sync.NullFieldCollector.java

private static String nameOf(Field field) {
    final XmlElementRef ref = field.getAnnotation(XmlElementRef.class);
    if (ref == null || StringUtils.isBlank(ref.name())) {
        return field.getName();
    } else {/*from w  w  w.  ja  v a2s .  co  m*/
        return ref.name();
    }
}