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.github.strawberry.redis.RedisLoader.java

private static Map<?, ?> nestedMapOf(Field field, Jedis jedis, Set<String> redisKeys) {
    Map map = mapImplementationOf(field.getType());
    for (String redisKey : redisKeys) {
        JedisType jedisType = JedisType.valueOf(jedis.type(redisKey).toUpperCase());
        switch (jedisType) {
        case STRING: {
            map.put(redisKey, jedis.get(redisKey));
        }// ww w  .ja  v  a 2  s . c  o m
            break;
        case HASH: {
            map.put(redisKey, jedis.hgetAll(redisKey));
        }
            break;
        case LIST: {
            map.put(redisKey, jedis.lrange(redisKey, 0, -1));
        }
            break;
        case SET: {
            map.put(redisKey, jedis.smembers(redisKey));
        }
            break;
        case ZSET: {
            map.put(redisKey, jedis.zrange(redisKey, 0, -1));
        }
            break;
        }
    }
    return map;
}

From source file:com.github.fcannizzaro.resourcer.Resourcer.java

/**
 * Check if field class is the expected class
 *//*from   ww  w . j  a v  a2s .  c o m*/
private static boolean is(Field field, Class expected) {
    return field.getType().equals(expected);
}

From source file:com.browseengine.bobo.serialize.JSONSerializer.java

public static JSONSerializable deSerialize(Class clz, JSONObject jsonObj)
        throws JSONSerializationException, JSONException {
    Iterator iter = jsonObj.keys();

    if (!JSONSerializable.class.isAssignableFrom(clz)) {
        throw new JSONSerializationException(clz + " is not an instance of " + JSONSerializable.class);
    }/*from www.  j  av a  2  s. c  o m*/

    JSONSerializable retObj;
    try {
        retObj = (JSONSerializable) clz.newInstance();
    } catch (Exception e1) {
        throw new JSONSerializationException(
                "trouble with no-arg instantiation of " + clz.toString() + ": " + e1.getMessage(), e1);
    }

    if (JSONExternalizable.class.isAssignableFrom(clz)) {
        ((JSONExternalizable) retObj).fromJSON(jsonObj);
        return retObj;
    }

    while (iter.hasNext()) {
        String key = (String) iter.next();

        try {
            Field f = clz.getDeclaredField(key);
            if (f != null) {
                f.setAccessible(true);
                Class type = f.getType();

                if (type.isArray()) {
                    JSONArray array = jsonObj.getJSONArray(key);
                    int len = array.length();
                    Class cls = type.getComponentType();

                    Object newArray = Array.newInstance(cls, len);
                    for (int k = 0; k < len; ++k) {
                        loadObject(newArray, cls, k, array);
                    }
                    f.set(retObj, newArray);
                } else {
                    loadObject(retObj, f, jsonObj);
                }
            }
        } catch (Exception e) {
            throw new JSONSerializationException(e.getMessage(), e);
        }
    }

    return retObj;
}

From source file:com.yiji.openapi.sdk.util.Reflections.java

public static Set<String> getSimpleFieldNames(Class<?> pojoClass) {
    Set<String> propertyNames = new HashSet<String>();
    Class<?> clazz = pojoClass;
    do {/*from   w w  w.  j  a v  a2 s . c o  m*/
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (!Modifier.isStatic(field.getModifiers()) && (field.getType().isPrimitive()
                    || isWrapClass(field.getType()) || field.getType().isAssignableFrom(Timestamp.class)
                    || field.getType().isAssignableFrom(Date.class)
                    || field.getType().isAssignableFrom(String.class)
                    || field.getType().isAssignableFrom(Calendar.class))) {
                propertyNames.add(field.getName());
            }
        }
        clazz = clazz.getSuperclass();
    } while (clazz != null && !clazz.getSimpleName().equalsIgnoreCase("Object"));
    return propertyNames;
}

From source file:br.com.renatoccosta.regexrenamer.element.base.ElementFactory.java

public static void setParameter(Element element, Field field, Object value) throws InvalidParameterException {
    try {//from   www.  ja v  a2  s.  c o m
        //for security reasons, only parameters can be set with this method
        if (field.getAnnotation(Parameter.class) != null) {
            if (value instanceof String) {
                value = utilsBean.getConvertUtils().convert((String) value, field.getType());
            }

            PropertyUtils.setProperty(element, field.getName(), value);
        } else {
            throw createInvalidParameterException(field.getName(), null);
        }
    } catch (Exception ex) {
        throw createInvalidParameterException(field.getName(), ex);
    }
}

From source file:it.nicola_amatucci.util.Json.java

public static <T> T object_from_json(JSONObject json, Class<T> objClass) throws Exception {
    T t = null;/*from   w  ww  .  ja  v  a2 s  .  c  om*/
    Object o = null;

    try {
        //create new object instance
        t = objClass.newInstance();

        //object fields
        Field[] fields = objClass.getFields();

        for (Field field : fields) {
            //field name
            o = json.get(field.getName());

            if (o.equals(null))
                continue;

            //field value
            try {
                String typeName = field.getType().getSimpleName();

                if (typeName.equals("String")) {
                    o = json.getString(field.getName()); //String
                } else if (typeName.equals("boolean")) {
                    o = Integer.valueOf(json.getInt(field.getName())); //boolean
                } else if (typeName.equals("int")) {
                    o = Integer.valueOf(json.getInt(field.getName())); //int
                } else if (typeName.equals("long")) {
                    o = Long.valueOf(json.getLong(field.getName())); //long                  
                } else if (typeName.equals("double")) {
                    o = Double.valueOf(json.getDouble(field.getName())); //double
                } else if (typeName.equals("Date")) {
                    o = new SimpleDateFormat(Json.DATA_FORMAT).parse(o.toString()); //data
                } else if (field.getType().isArray()) {
                    JSONArray arrayJSON = new JSONArray(o.toString());
                    T[] arrayOfT = (T[]) null;

                    try {
                        //create object array
                        Class c = Class.forName(field.getType().getName()).getComponentType();
                        arrayOfT = (T[]) Array.newInstance(c, arrayJSON.length());

                        //parse objects                  
                        for (int i = 0; i < json.length(); i++)
                            arrayOfT[i] = (T) object_from_json(arrayJSON.getJSONObject(i), c);
                    } catch (Exception e) {
                        throw e;
                    }

                    o = arrayOfT;
                } else {
                    o = object_from_json(new JSONObject(o.toString()), field.getType()); //object
                }

            } catch (Exception e) {
                throw e;
            }

            t.getClass().getField(field.getName()).set(t, o);
        }

    } catch (Exception e) {
        throw e;
    }

    return t;
}

From source file:activiti.common.persistence.util.ReflectHelper.java

/**
 * ?objfieldName/* www  . ja va2  s. co  m*/
 * 
 * @param obj
 * @param fieldName
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> T getValueByFieldType(Object obj, Class<T> fieldType) {
    Object value = null;
    for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
            .getSuperclass()) {
        try {
            Field[] fields = superClass.getDeclaredFields();
            for (Field f : fields) {
                if (f.getType() == fieldType) {
                    if (f.isAccessible()) {
                        value = f.get(obj);
                        break;
                    } else {
                        f.setAccessible(true);
                        value = f.get(obj);
                        f.setAccessible(false);
                        break;
                    }
                }
            }
            if (value != null) {
                break;
            }
        } catch (Exception e) {
        }
    }
    return (T) value;
}

From source file:edu.usu.sdl.openstorefront.validation.ValidationUtil.java

private static List<RuleResult> validateFields(final ValidationModel validateModel, Class dataClass,
        String parentFieldName, String parentType) {
    List<RuleResult> ruleResults = new ArrayList<>();

    if (validateModel.getDataObject() == null && validateModel.isAcceptNull() == false) {
        RuleResult validationResult = new RuleResult();
        validationResult.setMessage("The whole data object is null.");
        validationResult.setValidationRule("Don't allow null object");
        validationResult.setEntityClassName(parentType);
        validationResult.setFieldName(parentFieldName);
        ruleResults.add(validationResult);
    } else {/*w  w  w .  j  a  va  2s. c o m*/
        if (validateModel.getDataObject() != null) {
            if (dataClass.getSuperclass() != null) {
                ruleResults.addAll(validateFields(validateModel, dataClass.getSuperclass(), null, null));
            }

            for (Field field : dataClass.getDeclaredFields()) {
                Class fieldClass = field.getType();
                boolean process = true;
                if (validateModel.isConsumeFieldsOnly()) {
                    ConsumeField consumeField = (ConsumeField) field.getAnnotation(ConsumeField.class);
                    if (consumeField == null) {
                        process = false;
                    }
                }

                if (process) {
                    if (ReflectionUtil.isComplexClass(fieldClass)) {
                        //composition class
                        if (Logger.class.getName().equals(fieldClass.getName()) == false
                                && fieldClass.isEnum() == false) {
                            try {
                                Method method = validateModel.getDataObject().getClass().getMethod(
                                        "get" + StringUtils.capitalize(field.getName()), (Class<?>[]) null);
                                Object returnObj = method.invoke(validateModel.getDataObject(),
                                        (Object[]) null);
                                boolean check = true;
                                if (returnObj == null) {
                                    NotNull notNull = (NotNull) fieldClass.getAnnotation(NotNull.class);
                                    if (notNull == null) {
                                        check = false;
                                    }
                                }
                                if (check) {
                                    ruleResults.addAll(
                                            validateFields(ValidationModel.copy(validateModel, returnObj),
                                                    fieldClass, field.getName(),
                                                    validateModel.getDataObject().getClass().getSimpleName()));
                                }
                            } catch (NoSuchMethodException | SecurityException | IllegalAccessException
                                    | IllegalArgumentException | InvocationTargetException ex) {
                                throw new OpenStorefrontRuntimeException(ex);
                            }
                        }
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(List.class.getSimpleName())
                            || fieldClass.getSimpleName().equalsIgnoreCase(Map.class.getSimpleName())
                            || fieldClass.getSimpleName().equalsIgnoreCase(Collection.class.getSimpleName())
                            || fieldClass.getSimpleName().equalsIgnoreCase(Set.class.getSimpleName())) {
                        //multi
                        if (fieldClass.getSimpleName().equalsIgnoreCase(Map.class.getSimpleName())) {
                            try {
                                Method method = validateModel.getDataObject().getClass().getMethod(
                                        "get" + StringUtils.capitalize(field.getName()), (Class<?>[]) null);
                                Object returnObj = method.invoke(validateModel.getDataObject(),
                                        (Object[]) null);
                                Map mapObj = (Map) returnObj;
                                for (Object entryObj : mapObj.entrySet()) {
                                    ruleResults.addAll(
                                            validateFields(ValidationModel.copy(validateModel, entryObj),
                                                    entryObj.getClass(), field.getName(),
                                                    validateModel.getDataObject().getClass().getSimpleName()));
                                }
                            } catch (NoSuchMethodException | SecurityException | IllegalAccessException
                                    | IllegalArgumentException | InvocationTargetException ex) {
                                throw new OpenStorefrontRuntimeException(ex);
                            }
                        } else {
                            try {
                                Method method = validateModel.getDataObject().getClass().getMethod(
                                        "get" + StringUtils.capitalize(field.getName()), (Class<?>[]) null);
                                Object returnObj = method.invoke(validateModel.getDataObject(),
                                        (Object[]) null);
                                if (returnObj != null) {
                                    for (Object itemObj : (Collection) returnObj) {
                                        if (itemObj != null) {
                                            ruleResults.addAll(validateFields(
                                                    ValidationModel.copy(validateModel, itemObj),
                                                    itemObj.getClass(), field.getName(),
                                                    validateModel.getDataObject().getClass().getSimpleName()));
                                        } else {
                                            log.log(Level.WARNING,
                                                    "There is a NULL item in a collection.  Check data passed in to validation.");
                                        }
                                    }
                                } else {
                                    NotNull notNull = field.getAnnotation(NotNull.class);
                                    if (notNull != null) {
                                        RuleResult ruleResult = new RuleResult();
                                        ruleResult.setMessage("Collection is required");
                                        ruleResult.setEntityClassName(
                                                validateModel.getDataObject().getClass().getSimpleName());
                                        ruleResult.setFieldName(field.getName());
                                        ruleResult.setValidationRule("Requires value");
                                        ruleResults.add(ruleResult);
                                    }
                                }
                            } catch (NoSuchMethodException | SecurityException | IllegalAccessException
                                    | IllegalArgumentException | InvocationTargetException ex) {
                                throw new OpenStorefrontRuntimeException(ex);
                            }
                        }

                    } else {
                        //simple case
                        for (BaseRule rule : rules) {
                            //Stanize if requested
                            if (validateModel.getSantize()) {
                                Sanitize santize = field.getAnnotation(Sanitize.class);
                                if (santize != null) {
                                    try {
                                        Sanitizer santizer = santize.value().newInstance();

                                        Method method = dataClass.getMethod(
                                                "get" + StringUtils.capitalize(field.getName()),
                                                (Class<?>[]) null);
                                        Object returnObj = method.invoke(validateModel.getDataObject(),
                                                (Object[]) null);

                                        Object newValue = santizer.santize(returnObj);

                                        method = dataClass.getMethod(
                                                "set" + StringUtils.capitalize(field.getName()), String.class);
                                        method.invoke(validateModel.getDataObject(), newValue);

                                    } catch (InstantiationException | IllegalAccessException
                                            | NoSuchMethodException | SecurityException
                                            | InvocationTargetException ex) {
                                        throw new OpenStorefrontRuntimeException(ex);
                                    }
                                }
                            }

                            RuleResult validationResult = rule.processField(field,
                                    validateModel.getDataObject());
                            if (validationResult != null) {
                                ruleResults.add(validationResult);
                            }
                        }
                    }
                }
            }
        }
    }

    return ruleResults;
}

From source file:com.junly.common.util.ReflectUtils.java

/**
 * <p class="detail">/*from www .  j  a  va  2s.co  m*/
 * 
 * </p>
 * @author wan.Dong
 * @date 20161112 
 * @param obj 
 * @param name    ??
 * @param value  (?)??false
 * @return
 */
public static boolean setProperty(Object obj, String name, Object value) {
    if (obj != null) {
        Class<?> clazz = obj.getClass();
        while (clazz != null) {
            Field field = null;
            try {
                field = clazz.getDeclaredField(name);
            } catch (Exception e) {
                clazz = clazz.getSuperclass();
                continue;
            }
            try {
                Class<?> type = field.getType();
                if (type.isPrimitive() == true && value != null) {
                    if (value instanceof String) {
                        if (type.equals(int.class) == true) {
                            value = Integer.parseInt((String) value);
                        } else if (type.equals(double.class) == true) {
                            value = Double.parseDouble((String) value);
                        } else if (type.equals(boolean.class) == true) {
                            value = Boolean.parseBoolean((String) value);
                        } else if (type.equals(long.class) == true) {
                            value = Long.parseLong((String) value);
                        } else if (type.equals(byte.class) == true) {
                            value = Byte.parseByte((String) value);
                        } else if (type.equals(char.class) == true) {
                            value = Character.valueOf(((String) value).charAt(0));
                        } else if (type.equals(float.class) == true) {
                            value = Float.parseFloat((String) value);
                        } else if (type.equals(short.class) == true) {
                            value = Short.parseShort((String) value);
                        }
                    }
                    field.setAccessible(true);
                    field.set(obj, value);
                    field.setAccessible(false);
                }
                if (value == null || type.equals(value.getClass()) == true) {
                    field.setAccessible(true);
                    field.set(obj, value);
                    field.setAccessible(false);
                }
                return true;
            } catch (Exception e) {
                return false;
            }
        }
    }
    return false;
}

From source file:com.vmware.photon.controller.common.dcp.validation.NotBlankValidator.java

public static void validate(ServiceDocument state) {
    try {/*www  .j a va2 s .  co  m*/
        Field[] declaredFields = state.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            Annotation[] declaredAnnotations = field.getDeclaredAnnotations();
            for (Annotation annotation : declaredAnnotations) {
                if (annotation.annotationType() == NotBlank.class) {
                    checkState(null != field.get(state), String.format("%s cannot be null", field.getName()));
                    if (String.class.equals(field.getType())) {
                        checkState((StringUtils.isNotBlank((String) field.get(state))),
                                String.format("%s cannot be blank", field.getName()));
                    }
                }
            }
        }
    } catch (IllegalStateException e) {
        throw e;
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}