Example usage for java.lang.reflect Field getType

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

Introduction

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

Prototype

public Class<?> getType() 

Source Link

Document

Returns a Class object that identifies the declared type for the field represented by this Field object.

Usage

From source file:com.vk.sdk.api.model.ParseUtils.java

/**
* Parses object with follow rules:/*from  w  ww  .  j  ava 2  s  . c o  m*/
*
* 1. All fields should had a public access.
* 2. The name of the filed should be fully equal to name of JSONObject key.
* 3. Supports parse of all Java primitives, all {@link String},
* arrays of primitive types, {@link String}s and {@link com.vk.sdk.api.model.VKApiModel}s,
* list implementation line {@link com.vk.sdk.api.model.VKList}, {@link com.vk.sdk.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdk.api.model.VKPhotoSizes},
* {@link com.vk.sdk.api.model.VKApiModel}s.
*
* 4. Boolean fields defines by vk_int == 1 expression.
* @param object object to initialize
* @param source data to read values
* @return initialized according with given data object
* @throws JSONException if source object structure is invalid
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Parcelable.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            // ?????????? ???????:
            // ?? ?? ????????, ?? ? ????????? ???????? getFields() ???????? ??? ???.
            // ?????? ? ??????? ???????????, ????????? ?? ? ????????, ?????? Android ? ???????? ????????? ??????????.
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:com.vk.sdkweb.api.model.ParseUtils.java

/**
 * Parses object with follow rules://w w  w.j  a v a2  s  .  c  o  m
 *
 * 1. All fields should had a public access.
 * 2. The name of the filed should be fully equal to name of JSONObject key.
 * 3. Supports parse of all Java primitives, all {@link java.lang.String},
 *  arrays of primitive types, {@link java.lang.String}s and {@link com.vk.sdkweb.api.model.VKApiModel}s,
 *  list implementation line {@link com.vk.sdkweb.api.model.VKList}, {@link com.vk.sdkweb.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdkweb.api.model.VKPhotoSizes},
 *  {@link com.vk.sdkweb.api.model.VKApiModel}s.
 *
 * 4. Boolean fields defines by vk_int == 1 expression.
 *
 * @param object object to initialize
 * @param source data to read values
 * @param <T> type of result
 * @return initialized according with given data object
 * @throws JSONException if source object structure is invalid
 */
@SuppressWarnings("rawtypes")
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Parcelable.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            //  ?:
            //   ,     getFields()   .
            //  ? ? ?,   ? ?,  Android  ?  .
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:com.ghy.common.util.reflection.ReflectionUtils.java

/**
 * value String/*  w  w w.j a v a 2 s . c o  m*/
 * , private/protected, ??setter.
 */
public static void setFieldsValues(final Object obj, final String fieldName, final Object value) {
    Field field = getAccessibleField(obj, fieldName);

    if (field == null) {
        return;
    }

    try {
        Class<?> type = field.getType();
        if (type.equals(Integer.class) || type.equals(int.class)) {
            field.set(obj, Integer.valueOf((String) value));
        } else if (type.equals(Long.class) || type.equals(long.class)) {
            field.set(obj, Long.valueOf((String) value));
        } else if (type.equals(Double.class) || type.equals(double.class)) {
            field.set(obj, Double.valueOf((String) value));
        } else if (type.equals(Float.class) || type.equals(float.class)) {
            field.set(obj, Float.valueOf((String) value));
        } else if (type.equals(Boolean.class) || type.equals(boolean.class)) {
            field.set(obj, Boolean.valueOf((String) value));
        } else if (type.equals(Date.class)) {
            field.set(obj, new SimpleDateFormat("yyyyMMddHHmmsssss").parse((String) value));
        } else {
            field.set(obj, value);
        }
    } catch (IllegalAccessException e) {
        logger.error(":{}", e.getMessage());
    } catch (IllegalArgumentException e) {
        logger.error(":{}", e.getMessage());
        e.printStackTrace();
    } catch (ParseException e) {
        logger.error(":{}", e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.frame.base.utils.ReflectionUtils.java

/**
 * Setter. valueClass?Setter.//from   w w  w .  ja  v  a 2  s .  co  m
 * @throws NoSuchFieldException 
 * @throws SecurityException 
 */
public static void _invokeSetterMethod(Object obj, String propertyName, Object value) {
    String[] methods = StringUtils.split(propertyName, '.');
    int len = methods.length - 1;
    for (int i = 0; i < len; i++)
        obj = invokeGetter(obj, methods[i]);
    try {
        Field filed = obj.getClass().getDeclaredField(methods[len]);
        if (filed.getType().getSimpleName().equals("BigDecimal")) {
            invokeSetter(obj, methods[len], new BigDecimal(value.toString()));
        } else {
            invokeSetter(obj, methods[len], value);
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        invokeSetter(obj, methods[len], value);
    }

}

From source file:jfix.util.Reflections.java

/**
 * Retrieves all objects of given class-type which are referred by all the
 * objects in given collection.//  w  w  w . jav  a 2  s .com
 */
public static Set<Object> getReferredObjects(Collection<?> objects, Class<?> objectClass) {
    try {
        Set<Object> result = new HashSet<>();
        for (Object object : objects) {
            for (Field field : Reflections.getFields(object.getClass())) {
                if (isAssignable(objectClass, field)) {
                    Object fieldValue = field.get(object);
                    if (fieldValue != null) {
                        if (field.getType().isArray()) {
                            for (Object arrayElement : (Object[]) fieldValue) {
                                result.add(arrayElement);
                            }
                        } else {
                            result.add(fieldValue);
                        }
                    }
                }
            }
        }
        return result;
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:org.cybercat.automation.annotations.AnnotationBuilder.java

/**
 * @param entity/*from w w w.  jav a  2s.co  m*/
 * @param fields
 * @param i
 * @return
 * @throws AutomationFrameworkException
 */
@SuppressWarnings("unchecked")
private static <T> Class<AbstractFeature> processCCFeatureField(T entity, Field field)
        throws AutomationFrameworkException {
    Class<AbstractFeature> clazz;
    try {
        clazz = (Class<AbstractFeature>) field.getType();
    } catch (Exception e) {
        throw new AutomationFrameworkException("Unexpected field type :" + field.getType().getSimpleName()
                + " field name: " + field.getName() + " class: " + entity.getClass().getSimpleName()
                + " Thread ID:" + Thread.currentThread().getId()
                + " \n\tThis field must be of the type that extends AbstractPageObject class.", e);
    }
    try {
        field.set(entity, createFeature(versionControlPreprocessor(clazz)));
    } catch (Exception e) {
        throw new AutomationFrameworkException(
                "Set filed exception. Please, save this log and contact the Cybercat project support."
                        + " field name: " + field.getName() + " class: " + entity.getClass().getSimpleName()
                        + " Thread ID:" + Thread.currentThread().getId(),
                e);
    }
    return clazz;
}

From source file:com.ms.commons.test.common.ReflectUtil.java

public static void setValueToBean(Object bean, String field, Object value) {
    Class<?> clazz = bean.getClass();
    try {/*from   w ww .java  2 s .co  m*/
        Field f = getDeclaredField(clazz, NamingUtil.dbNameToJavaName(field));
        f.setAccessible(true);
        try {
            f.set(bean, TypeConvertUtil.convert(f.getType(), value));
        } catch (IllegalArgumentException e) {
            throw new UnknowException(e);
        } catch (IllegalAccessException e) {
            throw new UnknowException(e);
        }
    } catch (SecurityException e) {
        throw new UnknowException(e);
    } catch (NoSuchFieldException e) {
        throw new JavaFieldNotFoundException(clazz, field);
    }
}

From source file:gumga.framework.presentation.api.CSVGeneratorAPI.java

public static StringBuilder objectToCsvLine(Object gm) {
    StringBuilder sb = new StringBuilder();
    for (Field f : getAllAtributes(gm.getClass())) {
        try {// ww  w. j  a  v a 2s.c o  m
            f.setAccessible(true);
            if (f.get(gm) != null) {
                Field idField = getIdField(f.getType());
                if (idField != null) {
                    idField.setAccessible(true);
                    Object idValue = idField.get(f.get(gm));
                    sb.append(idValue.toString());
                } else if (f.getType().equals(Date.class)) {
                    sb.append(SDF.format(f.get(gm)));
                } else {
                    sb.append(f.get(gm).toString());
                }
            }
        } catch (Exception ex) {
            log.error("erro ao criar linha csv", ex);
        }
        sb.append(CSV_SEPARATOR);
    }
    sb.deleteCharAt(sb.length() - 1);
    sb.append(CSV_LINE_DELIMITER);
    return sb;
}

From source file:com.facebook.presto.hive.TestPrestoS3FileSystem.java

@SuppressWarnings("unchecked")
private static <T> T getFieldValue(Object instance, Class<?> clazz, String name, Class<T> type) {
    try {// w  w  w .j a va  2  s  .co  m
        Field field = clazz.getDeclaredField(name);
        checkArgument(field.getType() == type, "expected %s but found %s", type, field.getType());
        field.setAccessible(true);
        return (T) field.get(instance);
    } catch (ReflectiveOperationException e) {
        throw Throwables.propagate(e);
    }
}

From source file:cn.afterturn.easypoi.util.PoiPublicUtil.java

/**
 * ?java/*  w  w  w .j  ava  2 s. co m*/
 *
 * @param field
 * @return
 */
public static boolean isJavaClass(Field field) {
    Class<?> fieldType = field.getType();
    boolean isBaseClass = false;
    if (fieldType.isArray()) {
        isBaseClass = false;
    } else if (fieldType.isPrimitive() || fieldType.getPackage() == null
            || "java.lang".equals(fieldType.getPackage().getName())
            || "java.math".equals(fieldType.getPackage().getName())
            || "java.sql".equals(fieldType.getPackage().getName())
            || "java.time".equals(fieldType.getPackage().getName())
            || "java.util".equals(fieldType.getPackage().getName())) {
        isBaseClass = true;
    }
    return isBaseClass;
}