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.qumoon.commons.BeanMapper.java

public static <T> T convertProto2Bean(com.google.protobuf.GeneratedMessage message, T descObject,
        Class srcClass) {/* www.ja  v a2  s . c  o m*/
    for (Field srcField : srcClass.getDeclaredFields()) {
        Descriptors.FieldDescriptor fd = message.getDescriptorForType().findFieldByName(srcField.getName());
        if (null == fd) {
            continue;
        }
        try {
            String fieldStrValue = String.valueOf(message.getField(fd));
            if (fieldStrValue.isEmpty()) {
                continue;
            }
            if (srcField.getType() == BigDecimal.class) {
                PropertyUtils.setProperty(descObject, srcField.getName(), new BigDecimal(fieldStrValue));
            } else {
                if (srcField.getType() == Date.class) {
                    PropertyUtils.setProperty(descObject, srcField.getName(),
                            new Date((Long) (message.getField(fd))));
                } else {
                    if (srcField.getType() == Byte.class) {
                        PropertyUtils.setProperty(descObject, srcField.getName(), Byte.valueOf(fieldStrValue));
                    } else {
                        PropertyUtils.setProperty(descObject, srcField.getName(), message.getField(fd));
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            continue;
        }
    }
    return descObject;
}

From source file:cn.wanghaomiao.seimi.core.SeimiBeanResolver.java

private static Object defaultCastToTargetValue(Class target, Field field, List<Object> xpathRes) {
    Method getter = ReflectionUtils.findMethod(target, "get" + upperFirst(field.getName()));
    if (getter != null) {
        if (List.class.equals(getter.getReturnType())) {
            Class[] componentClazzs = GenericUtils.getActualClass(getter.getGenericReturnType());
            if (componentClazzs != null && componentClazzs.length > 0) {
                Class componentClass = componentClazzs[0];
                if (String.class.isAssignableFrom(componentClass)) {
                    List<String> resTmp = new LinkedList<>();
                    for (Object obj : xpathRes) {
                        if (obj instanceof Element) {
                            resTmp.add(((Element) obj).html());
                        } else {
                            resTmp.add(obj.toString());
                        }//ww w .j ava 2  s  .  com
                    }
                    return resTmp;
                } else if (Element.class.isAssignableFrom(componentClass)) {
                    return xpathRes;
                } else if (GenericUtils.isNumber(componentClass)) {
                    List resTmp = new LinkedList();
                    for (Object obj : xpathRes) {
                        resTmp.add(GenericUtils.castToNumber(componentClass, obj.toString()));
                    }
                    return resTmp;
                } else {
                    throw new SeimiBeanResolveException("not support field type");
                }
            }
        } else if (!Collection.class.isAssignableFrom(getter.getReturnType())
                && getter.getReturnType().isArray()) {
            Class componentClass = getter.getReturnType().getComponentType();
            if (String.class.isAssignableFrom(componentClass)) {
                List<String> resTmp = new LinkedList<>();
                for (Object obj : xpathRes) {
                    if (obj instanceof Element) {
                        resTmp.add(((Element) obj).html());
                    } else {
                        resTmp.add(obj.toString());
                    }
                }
                return resTmp;
            } else if (Element.class.isAssignableFrom(componentClass)) {
                return xpathRes;
            } else if (GenericUtils.isNumber(componentClass)) {
                List resTmp = new LinkedList();
                for (Object obj : xpathRes) {
                    resTmp.add(GenericUtils.castToNumber(componentClass, obj.toString()));
                }
                return resTmp;
            } else {
                throw new SeimiBeanResolveException("not support field type");
            }
        } else if (!Collection.class.isAssignableFrom(getter.getReturnType())
                && GenericUtils.isNumber(field.getType())) {
            return GenericUtils.castToNumber(field.getType(), StringUtils.join(xpathRes, ""));
        } else if (!Collection.class.isAssignableFrom(getter.getReturnType())
                && String.class.isAssignableFrom(field.getType())) {
            return StringUtils.join(xpathRes, "");
        }
    }
    return null;
}

From source file:com.hortonworks.registries.common.util.ReflectionHelper.java

/**
 * Given a class, this method returns a map of names of all the instance (non static) fields to type.
 * if the class has any super class it also includes those fields.
 * @param clazz , not null//from  w ww.ja v  a  2  s .  c  o m
 * @return
 */
public static Map<String, Class> getFieldNamesToTypes(Class clazz) {
    Field[] declaredFields = clazz.getDeclaredFields();
    Map<String, Class> instanceVariableNamesToTypes = new HashMap<>();
    for (Field field : declaredFields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            LOG.trace("clazz {} has field {} with type {}", clazz.getName(), field.getName(),
                    field.getType().getName());
            instanceVariableNamesToTypes.put(field.getName(), field.getType());
        } else {
            LOG.trace("clazz {} has field {} with type {}, which is static so ignoring", clazz.getName(),
                    field.getName(), field.getType().getName());
        }
    }

    if (!clazz.getSuperclass().equals(Object.class)) {
        instanceVariableNamesToTypes.putAll(getFieldNamesToTypes(clazz.getSuperclass()));
    }
    return instanceVariableNamesToTypes;
}

From source file:lite.flow.util.ActivityInspector.java

protected static FieldInfo[] discoverParameters(Class<?> clazz) {
    Field[] fields = FieldUtils.getFieldsWithAnnotation(clazz, Parameter.class);
    FieldInfo[] fieldInfos = new FieldInfo[fields.length];
    for (int i = 0; i < fieldInfos.length; i++) {
        Field field = fields[i];
        fieldInfos[i] = new FieldInfo(field.getName(), field.getType());
    }/*from   w w w  .  j  a  v  a  2  s .c om*/

    return fieldInfos;
}

From source file:lite.flow.util.ActivityInspector.java

protected static FieldInfo[] discoverResources(Class<?> clazz) {
    Field[] fields = FieldUtils.getFieldsWithAnnotation(clazz, Resource.class);
    FieldInfo[] fieldInfos = new FieldInfo[fields.length];
    for (int i = 0; i < fieldInfos.length; i++) {
        Field field = fields[i];
        fieldInfos[i] = new FieldInfo(field.getName(), field.getType());
    }/*from  w w w.ja va 2 s.  c om*/

    return fieldInfos;
}

From source file:com.antsdb.saltedfish.util.CursorUtil.java

public static CursorMeta toMeta(Class<?> klass) {
    CursorMeta meta = new CursorMeta();
    for (Field i : klass.getFields()) {
        FieldMeta column = new FieldMeta();
        column.setName(i.getName());
        if (i.getType() == String.class) {
            column.setType(DataType.varchar());
        } else if (i.getType() == int.class) {
            column.setType(DataType.integer());
        } else if (i.getType() == Integer.class) {
            column.setType(DataType.integer());
        } else if (i.getType() == long.class) {
            column.setType(DataType.longtype());
        } else if (i.getType() == Long.class) {
            column.setType(DataType.longtype());
        } else if (i.getType() == Timestamp.class) {
            column.setType(DataType.timestamp());
        } else if (i.getType() == byte[].class) {
            column.setType(DataType.blob());
        } else {//from w  w w .  jav a 2  s  .co m
            throw new NotImplementedException();
        }
        meta.addColumn(column);
    }
    return meta;
}

From source file:io.tilt.minka.utils.Defaulter.java

private static PropertyEditor edit(final Properties props, final Object configurable, final Field staticField,
        final Field instanceField) throws IllegalAccessException {

    staticField.setAccessible(true);/*  www . ja va 2 s .  co  m*/
    final String name = instanceField.getName();
    final String staticValue = staticField.get(configurable).toString();
    final Object propertyOrDefault = props.getProperty(name, System.getProperty(name, staticValue));
    final String objName = configurable.getClass().getSimpleName();
    final PropertyEditor editor = PropertyEditorManager.findEditor(instanceField.getType());
    final String setLog = "Defaulter: set <{}> field [{}] = '{}' from {} ";
    try {
        editor.setAsText(propertyOrDefault.toString());
        logger.info(setLog, objName, name, editor.getValue(),
                propertyOrDefault != staticValue ? " property " : staticField.getName());
    } catch (Exception e) {
        logger.error(
                "Defaulter: object <{}> field: {} does not accept property or static "
                        + "default value: {} (reason: {})",
                objName, name, propertyOrDefault, e.getClass().getSimpleName());
        try { // at this moment only prop. might've been failed
            editor.setAsText(staticValue);
            logger.info(setLog, objName, name, editor.getValue(), staticField.getName());
        } catch (Exception e2) {
            final StringBuilder sb = new StringBuilder().append("Defaulter: object <").append(objName)
                    .append("> field: ").append(name).append(" does not accept static default value: ")
                    .append(propertyOrDefault).append(" (reason: ").append(e.getClass().getSimpleName())
                    .append(")");
            throw new RuntimeException(sb.toString());
        }

    }

    return editor;
}

From source file:org.shept.persistence.provider.hibernate.HibernateUtils_old.java

/**
 * Checking if it is a new model/*  ww  w.  j  a v a2s  .  c o  m*/
 * If the index is a compound index we must check all components if they are all non null
 * @param index
 * @return
 */
public static boolean isNewModel(HibernateDaoSupport dao, Object model) {
    final Object index = getIdValue(dao, model);
    final List<Field> nulls = new ArrayList<Field>();
    if (index == null)
        return true;

    ReflectionUtils.doWithFields(index.getClass(), new ReflectionUtils.FieldCallback() {
        public void doWith(Field field) {
            try {
                Method idMth = ReflectionUtils.findMethod(index.getClass(),
                        "get" + StringUtils.capitalize(field.getName()));
                Object value = ReflectionUtils.invokeMethod(idMth, index);
                if (value == null) {
                    nulls.add(field);
                }
            } catch (Exception ex) {
                // ignore all Exception here as they are quit frequent
                // e.g. serialVersionUid e.t.c. or do better filtering
                // TODO better eliminate error cases
            }
        }
    });
    return nulls.size() > 0;
}

From source file:com.scvngr.levelup.core.test.JsonTestUtil.java

/**
 * <p>/* w  w w  .  j av  a  2  s. com*/
 * Checks that modifying individual fields in a model will result in its equals/hashCode methods
 * failing. Uses reflection on {@link JsonValueType} annotations on fields of a passed class to
 * figure out how to modify the JSON representation of the model in different ways, then parses
 * the JSON with a {@link AbstractJsonModelFactory} subclass before checking equals/hashcode on
 * both the original and a modified object.
 * </p>
 * <p>
 * This effectively checks that equals/hashcode works across any value changes from fields we
 * read from JSON, but also checks some other potential issues. We're implicitly checking that
 * the JSON typing declared in annotations for the fields matches what we actually use when
 * parsing our JSON (since if it doesn't, we'll get JSON errors when reading the data during the
 * clone/modify). We're also checking for fields that may have been added to the JSON keys and
 * the model without updating equals/hashcode to reflect them (as long as they're declared in
 * the JSONKeys class used here).
 * </p>
 * <p>
 * Note that this is only intended for test use and will turn all checked exceptions it might
 * throw into unchecked ones.
 * </p>
 *
 * @param jsonKeysClass Class of the underlying keys class to test all fields (except
 *        blacklistFields) from. Must have visible fields to read from.
 * @param jsonFactory Factory object to construct model instances from out of the base and
 *        generated-variant JSON objects before checking equals/hashcode.
 * @param baseJsonObject Fully-populated JSON object for the model to use for comparison with
 *        modified copies.
 * @param blacklistFields Fields to exclude from variant testing (either because we need to test
 *        them manually or because they don't reflect fields that are used for parsing into the
 *        model). Note that this is the jsonKeysClass's field name as a string, not the JSON key
 *        value (eg "ID", not "id").
 */
public static void checkEqualsAndHashCodeOnJsonVariants(@NonNull final Class<?> jsonKeysClass,
        @NonNull final AbstractJsonModelFactory<?> jsonFactory, @NonNull final JSONObject baseJsonObject,
        @NonNull final String[] blacklistFields) {
    Object originalModel;
    Object differentModel;
    Object differentModelReparse;

    try {
        originalModel = jsonFactory.from(baseJsonObject);
    } catch (final JSONException e1) {
        throw new RuntimeException(e1);
    }

    MoreAsserts.checkEqualsAndHashCodeMethods(originalModel, null, false);

    final Field[] jsonKeyFields = jsonKeysClass.getFields();
    final List<String> blacklisted = Arrays.asList(blacklistFields);
    final String key = null;

    MoreAsserts.assertNotEmpty("JSON keys class visible fields", Arrays.asList(jsonKeyFields));

    for (final Field field : jsonKeyFields) {
        if (!blacklisted.contains(field.getName())) {
            JSONObject copiedDifferingObject;
            String fieldString;
            // Don't check exceptions, just let tests fail.
            try {
                fieldString = NullUtils.nonNullContract((String) field.get(key));
                copiedDifferingObject = cloneObjectDifferingOnParam(baseJsonObject, fieldString,
                        reflectJsonType(field));
                differentModel = jsonFactory.from(copiedDifferingObject);
                differentModelReparse = jsonFactory.from(copiedDifferingObject);
            } catch (final IllegalArgumentException e) {
                throw new RuntimeException(e);
            } catch (final IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (final JSONException e) {
                throw new RuntimeException(e);
            }

            MoreAsserts.checkEqualsAndHashCodeMethods(
                    String.format(Locale.US, "Modified %s and checked equals and hash", fieldString),
                    originalModel, differentModel, false);
            MoreAsserts.checkEqualsAndHashCodeMethods(
                    String.format(Locale.US, "Modified %s and checked equals and hash", fieldString),
                    differentModel, differentModel, true);
            MoreAsserts.checkEqualsAndHashCodeMethods(
                    String.format(Locale.US, "Modified %s and checked equals and hash", fieldString),
                    differentModel, differentModelReparse, true);
        }
    }
}

From source file:Main.java

/**
 * Coverter./*from www .j  a va2s  .  co  m*/
 *
 * @param object
 *            the object
 * @return the string
 */
@SuppressWarnings("unused")
public static String coverter(Object object) {
    if (object instanceof Object[]) {
        return coverter((Object[]) object);
    }
    if (object instanceof Collection) {
        return coverter((Collection<?>) object);
    }
    StringBuilder strBuilder = new StringBuilder();
    if (isObject(object)) {
        Class<? extends Object> clz = object.getClass();
        Field[] fields = clz.getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            if (field == null) {
                continue;
            }
            String fieldName = field.getName();
            Object value = null;
            try {
                value = field.get(object);
            } catch (IllegalArgumentException e) {
                continue;
            } catch (IllegalAccessException e) {
                continue;
            }
            strBuilder.append("<").append(fieldName).append(" className=\"").append(value.getClass().getName())
                    .append("\">\n");
            strBuilder.append(value.toString() + "\n");
            strBuilder.append("</").append(fieldName).append(">\n");
        }
    } else if (object == null) {
        strBuilder.append("null");
    } else {
        strBuilder.append(object.toString());
    }
    return strBuilder.toString();
}