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.rvesse.airline.Accessor.java

@SuppressWarnings("unchecked")
private static Collection<Object> getOrCreateCollectionField(String name, Object object, Field field) {
    Collection<Object> collection;
    try {/*from w  w  w .jav a  2 s  .co  m*/
        collection = (Collection<Object>) field.get(object);
    } catch (Exception e) {
        throw new ParseException(e, "Error getting collection field %s for argument %s", field.getName(), name);
    }

    if (collection == null) {
        collection = newCollection(field.getType());
        try {
            field.set(object, collection);
        } catch (Exception e) {
            throw new ParseException(e, "Error setting collection field %s for argument %s", field.getName(),
                    name);
        }
    }
    return collection;
}

From source file:com.github.strawberry.redis.RedisLoader.java

private static Option loadFromRedis(JedisPool pool, final Field field, final Redis annotation) {
    return using(pool)._do(new F<Jedis, Option>() {

        @Override//from w w w.j a  v  a  2  s.co m
        public Option f(Jedis jedis) {
            Object value = null;

            Class<?> fieldType = field.getType();

            String pattern = annotation.value();
            boolean allowNull = annotation.allowNull();

            Set<String> redisKeys = Sets.newTreeSet(jedis.keys(pattern));
            if (redisKeys.size() == 1) {
                String redisKey = Iterables.getOnlyElement(redisKeys);
                if (fieldType.equals(char[].class)) {
                    value = jedis.get(redisKey).toCharArray();
                } else if (fieldType.equals(Character[].class)) {
                    value = ArrayUtils.toObject(jedis.get(redisKey).toCharArray());
                } else if (fieldType.equals(char.class) || fieldType.equals(Character.class)) {
                    String toConvert = jedis.get(redisKey);
                    if (toConvert.length() == 1) {
                        value = jedis.get(redisKey).charAt(0);
                    } else {
                        throw ConversionException.of(toConvert, redisKey, fieldType);
                    }
                } else if (fieldType.equals(String.class)) {
                    value = jedis.get(redisKey);
                } else if (fieldType.equals(byte[].class)) {
                    value = jedis.get(redisKey.getBytes());
                } else if (fieldType.equals(Byte[].class)) {
                    value = ArrayUtils.toObject(jedis.get(redisKey.getBytes()));
                } else if (fieldType.equals(boolean.class) || fieldType.equals(Boolean.class)) {
                    String toConvert = jedis.get(redisKey);
                    if (BOOLEAN.matcher(toConvert).matches()) {
                        value = TRUE.matcher(toConvert).matches();
                    } else {
                        throw ConversionException.of(toConvert, redisKey, fieldType);
                    }
                } else if (Map.class.isAssignableFrom(fieldType)) {
                    value = mapOf(field, jedis, redisKey);
                } else if (Collection.class.isAssignableFrom(fieldType)) {
                    value = collectionOf(field, jedis, redisKey);
                } else {
                    String toConvert = jedis.get(redisKey);
                    try {
                        if (fieldType.equals(byte.class) || fieldType.equals(Byte.class)) {
                            value = Byte.parseByte(jedis.get(redisKey));
                        } else if (fieldType.equals(short.class) || fieldType.equals(Short.class)) {
                            value = Short.parseShort(toConvert);
                        } else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) {
                            value = Integer.parseInt(toConvert);
                        } else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) {
                            value = Long.parseLong(toConvert);
                        } else if (fieldType.equals(BigInteger.class)) {
                            value = new BigInteger(toConvert);
                        } else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) {
                            value = Float.parseFloat(toConvert);
                        } else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) {
                            value = Double.parseDouble(toConvert);
                        } else if (fieldType.equals(BigDecimal.class)) {
                            value = new BigDecimal(toConvert);
                        }
                    } catch (NumberFormatException exception) {
                        throw ConversionException.of(exception, toConvert, redisKey, fieldType);
                    }
                }
            } else if (redisKeys.size() > 1) {
                if (Map.class.isAssignableFrom(fieldType)) {
                    value = nestedMapOf(field, jedis, redisKeys);
                } else if (Collection.class.isAssignableFrom(fieldType)) {
                    value = nestedCollectionOf(field, jedis, redisKeys);
                }
            } else {
                if (!allowNull) {
                    value = nonNullValueOf(fieldType);
                }
            }
            return Option.fromNull(value);
        }
    });
}

From source file:Main.java

public static Object isEmpty(Object obj, Class clazz) {
    if (obj == null || clazz == null) {
        return obj;
    }//from   w w  w.  j a va 2  s  . com
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        try {
            String fieldName = field.getName();
            if (fieldName == null || fieldName.length() == 0)
                continue;
            String fieldMethodName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            String getfieldName = "get" + fieldMethodName;
            Method getMethod = clazz.getMethod(getfieldName, null);
            if (getMethod == null)
                continue;
            Object value = getMethod.invoke(obj, null);
            Class type = field.getType();
            if (type == String.class) {
                if (value == null || "null".equals(value.toString()) || value.toString().trim().length() == 0) {
                    value = "";
                    String setfieldName = "set" + fieldMethodName;
                    Method setMethod = clazz.getMethod(setfieldName, String.class);
                    if (setMethod == null)
                        continue;
                    setMethod.invoke(obj, value);
                }
            } else if (type == Integer.class || type == int.class || type == Float.class || type == float.class
                    || type == Double.class || type == double.class) {
                if (value == null || "null".equals(value.toString()) || value.toString().length() == 0) {
                    String setfieldName = "set" + fieldMethodName;
                    Method setMethod = clazz.getMethod(setfieldName, type);
                    setMethod.invoke(obj, 0);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            continue;
        }
    }
    return obj;
}

From source file:net.sourceforge.stripes.integration.spring.SpringHelper.java

/**
 * Looks for all methods and fields annotated with {@code @SpringBean} and attempts
 * to lookup and inject a managed bean into the field/property. If any annotated
 * element cannot be injected an exception is thrown.
 *
 * @param bean the bean into which to inject spring beans
 * @param ctx the Spring application context
 *///from  w w w  . j a v  a 2  s.  c o m
public static void injectBeans(Object bean, ApplicationContext ctx) {
    // First inject any values using annotated methods
    for (Method m : getMethods(bean.getClass())) {
        try {
            SpringBean springBean = m.getAnnotation(SpringBean.class);
            boolean nameSupplied = !"".equals(springBean.value());
            String name = nameSupplied ? springBean.value() : methodToPropertyName(m);
            Class<?> beanType = m.getParameterTypes()[0];
            Object managedBean = findSpringBean(ctx, name, beanType, !nameSupplied);
            m.invoke(bean, managedBean);
        } catch (Exception e) {
            throw new StripesRuntimeException(
                    "Exception while trying to lookup and inject " + "a Spring bean into a bean of type "
                            + bean.getClass().getSimpleName() + " using method " + m.toString(),
                    e);
        }
    }

    // And then inject any properties that are annotated
    for (Field f : getFields(bean.getClass())) {
        try {
            SpringBean springBean = f.getAnnotation(SpringBean.class);
            boolean nameSupplied = !"".equals(springBean.value());
            String name = nameSupplied ? springBean.value() : f.getName();
            Object managedBean = findSpringBean(ctx, name, f.getType(), !nameSupplied);
            f.set(bean, managedBean);
        } catch (Exception e) {
            throw new StripesRuntimeException(
                    "Exception while trying to lookup and inject " + "a Spring bean into a bean of type "
                            + bean.getClass().getSimpleName() + " using field access on field " + f.toString(),
                    e);
        }
    }
}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

public static boolean isByRef(Field field) {

    Annotation[] fieldAnnotations = field.getAnnotations();
    Class<?> type = field.getType();
    return isByRef(type, fieldAnnotations);
}

From source file:com.nridge.core.base.field.data.DataBeanBag.java

private static DataField reflectField(Object anObject, Field aField)
        throws NoSuchFieldException, IllegalAccessException {
    DataField dataField;//from   w  w w.  j  a v a  2  s  .  c o m
    String fieldName, fieldValue, fieldTitle;
    com.nridge.core.base.field.Field.Type fieldType;

    fieldName = aField.getName();
    fieldTitle = com.nridge.core.base.field.Field.nameToTitle(fieldName);

    Class<?> classFieldType = aField.getType();
    Object fieldObject = aField.get(anObject);

    if ((StringUtils.endsWith(classFieldType.getName(), "Integer"))
            || (StringUtils.endsWith(classFieldType.getName(), "int"))) {
        fieldType = com.nridge.core.base.field.Field.Type.Integer;
        fieldValue = fieldObject.toString();
        dataField = new DataField(fieldType, fieldName, fieldTitle, fieldValue);
    } else if ((StringUtils.endsWith(classFieldType.getName(), "Float"))
            || (StringUtils.endsWith(classFieldType.getName(), "float"))) {
        fieldType = com.nridge.core.base.field.Field.Type.Float;
        fieldValue = fieldObject.toString();
        dataField = new DataField(fieldType, fieldName, fieldTitle, fieldValue);
    } else if ((StringUtils.endsWith(classFieldType.getName(), "Double"))
            || (StringUtils.endsWith(classFieldType.getName(), "double"))) {
        fieldType = com.nridge.core.base.field.Field.Type.Double;
        fieldValue = fieldObject.toString();
        dataField = new DataField(fieldType, fieldName, fieldTitle, fieldValue);
    } else if ((StringUtils.endsWith(classFieldType.getName(), "Boolean"))
            || (StringUtils.endsWith(classFieldType.getName(), "boolean"))) {
        fieldType = com.nridge.core.base.field.Field.Type.Boolean;
        fieldValue = fieldObject.toString();
        dataField = new DataField(fieldType, fieldName, fieldTitle, fieldValue);
    } else if (StringUtils.endsWith(classFieldType.getName(), "Date")) {
        fieldType = com.nridge.core.base.field.Field.Type.Date;
        Date fieldDate = (Date) fieldObject;
        fieldValue = com.nridge.core.base.field.Field.dateValueFormatted(fieldDate, null);
        dataField = new DataField(fieldType, fieldName, fieldTitle, fieldValue);
    } else {
        fieldType = com.nridge.core.base.field.Field.Type.Text;
        if (fieldObject instanceof String[]) {
            String[] fieldValues = (String[]) fieldObject;
            dataField = new DataField(fieldType, fieldName, fieldTitle);
            dataField.setMultiValueFlag(true);
            dataField.setValues(fieldValues);
        } else if (fieldObject instanceof Collection) {
            ArrayList<String> fieldValues = (ArrayList<String>) fieldObject;
            dataField = new DataField(fieldType, fieldName, fieldTitle);
            dataField.setMultiValueFlag(true);
            dataField.setValues(fieldValues);
        } else {
            fieldValue = fieldObject.toString();
            dataField = new DataField(fieldType, fieldName, fieldTitle, fieldValue);
        }
    }

    return dataField;
}

From source file:edu.usu.sdl.openstorefront.core.util.EntityUtil.java

/**
 * This will set default on the fields that are marked with a default and
 * are null//from  w  w w.j a v a2 s.  com
 *
 * @param entity
 */
public static void setDefaultsOnFields(Object entity) {
    Objects.requireNonNull(entity, "Entity must not be NULL");
    List<Field> fields = getAllFields(entity.getClass());
    for (Field field : fields) {
        DefaultFieldValue defaultFieldValue = field.getAnnotation(DefaultFieldValue.class);
        if (defaultFieldValue != null) {
            field.setAccessible(true);
            try {
                if (field.get(entity) == null) {
                    String value = defaultFieldValue.value();
                    Class fieldClass = field.getType();
                    if (fieldClass.getSimpleName().equalsIgnoreCase(String.class.getSimpleName())) {
                        field.set(entity, value);
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Long.class.getSimpleName())) {
                        field.set(entity, value);
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Integer.class.getSimpleName())) {
                        field.set(entity, Integer.parseInt(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Boolean.class.getSimpleName())) {
                        field.set(entity, Convert.toBoolean(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Double.class.getSimpleName())) {
                        field.set(entity, Double.parseDouble(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Float.class.getSimpleName())) {
                        field.set(entity, Float.parseFloat(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(BigDecimal.class.getSimpleName())) {
                        field.set(entity, Convert.toBigDecimal(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Date.class.getSimpleName())) {
                        field.set(entity, TimeUtil.fromString(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(BigInteger.class.getSimpleName())) {
                        field.set(entity, new BigInteger(value));
                    }
                }
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                throw new OpenStorefrontRuntimeException(
                        "Unable to get value on " + entity.getClass().getName(), "Check entity passed in.");
            }
        }
    }
}

From source file:com.github.dozermapper.core.util.ReflectionUtils.java

private static boolean isAutoboxingSetter(Method method, String setterMethodName, Field field) {
    return method.getName().equals(setterMethodName) && method.getParameterTypes().length == 1
            && canBeAutoboxed(method.getParameterTypes()[0], field.getType());
}

From source file:com.mmj.app.common.file.ExcelUtils.java

/**
 * ?BeanMAP/*from w w w  .  jav  a2 s .  c  o m*/
 */
public static Map<String, String> getFieldValueMap(Object bean) {
    Class<?> cls = bean.getClass();
    Map<String, String> valueMap = new LinkedHashMap<String, String>();
    Field[] fields = getAllFields(new ArrayList<Field>(), cls);

    for (Field field : fields) {
        try {
            if (field == null || field.getName() == null) {
                continue;
            }
            if (StringUtils.equals("serialVersionUID", field.getName())) {
                continue;
            }

            Object fieldVal = PropertyUtils.getProperty(bean, field.getName());

            String result = null;
            if (null != fieldVal) {
                if (StringUtils.equals("Date", field.getType().getSimpleName())) {
                    result = DateViewTools.format((Date) fieldVal, "yyyy-MM-dd HH:mm:ss");
                } else {
                    result = String.valueOf(fieldVal);
                }
            }
            valueMap.put(field.getName(), result == null ? StringUtils.EMPTY : result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            continue;
        }
    }
    return valueMap;
}

From source file:com.greenline.hrs.admin.cache.redis.util.RedisInfoParser.java

/**
 * RedisInfoMapT?RedisInfoMapRedis?//  w  ww.  j  a v  a  2 s . c o m
 * RedisServerInfoPO
 *
 * @param instanceType class
 * @param redisInfoMap Map
 * @param <T>          
 * @return instanceTypeinfomapnullinfoMap?instancenullRedisServerInfoPO
 */
public static <T> T parserRedisInfo(Class<T> instanceType, Map<String, String> redisInfoMap) {
    if (instanceType == null || redisInfoMap == null || redisInfoMap.isEmpty()) {
        return null;
    }
    T instance = null;
    try {
        instance = instanceType.newInstance();
    } catch (Exception e) {
        LOG.error("Instance:" + instanceType.getName(), e);
        return null;
    }
    Field[] fields = instanceType.getDeclaredFields();
    String inputName = null;
    for (Field field : fields) {
        ParserField parserField = field.getAnnotation(ParserField.class);
        if (parserField != null) {
            inputName = parserField.inputName();
        } else {
            inputName = field.getName();
        }
        if (redisInfoMap.containsKey(inputName)) {
            field.setAccessible(true);
            try {
                field.set(instance, ConvertUtils.convert(redisInfoMap.get(inputName), field.getType()));
            } catch (Exception e) {
                LOG.error("Field:" + field.getName() + "\t|\t value:" + redisInfoMap.get(inputName), e);
            }
        }
    }
    return instance;
}