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:Main.java

public static <C> C cloneObject(C original) {
    try {/* w  ww  . j a va  2 s . c o  m*/
        C clone = (C) original.getClass().newInstance();
        for (Field field : getAllFieldsValues(original.getClass())) {
            field.setAccessible(true);
            if (field.get(original) == null || Modifier.isFinal(field.getModifiers())) {
                continue;
            }
            if (field.getType().isPrimitive() || field.getType().equals(String.class)
                    || field.getType().getSuperclass().equals(Number.class)
                    || field.getType().equals(Boolean.class)) {
                field.set(clone, field.get(original));
            } else {
                Object childObj = field.get(original);
                if (childObj == original) {
                    field.set(clone, clone);
                } else {
                    field.set(clone, cloneObject(field.get(original)));
                }
            }
        }
        return clone;
    } catch (Exception e) {
        return null;
    }
}

From source file:au.com.dw.testdatacapturej.reflection.util.ReflectionUtil.java

/**
 * Get the class name from a reflection Field, used when object isn't available, e.g. null value.
 *
 * @param field//from w w w .  j  a v  a 2  s.  c o m
 * @return
 */
public static String getClassNameFromField(Field field) {
    return field.getType().getName();
}

From source file:com.qualogy.qafe.business.integration.adapter.MappingAdapter.java

private static Object adaptToJavaObject(String mappingId, String attributeName, Object result,
        Object valueToAdapt, ClassLoader classLoader) {
    try {//from   w w w.j a  v  a  2s .  c o  m
        if (valueToAdapt != null) {
            Class resultClazz = classLoader.loadClass(result.getClass().getName());

            Field field = resultClazz.getDeclaredField(attributeName);
            field.setAccessible(true);
            String fieldName = field.getType().getName();
            String valueName = valueToAdapt.getClass().getName();
            logger.info(field.getType().getName());

            if (!fieldName.equals(valueName)) {
                if (PredefinedClassTypeConverter.isPredefined(field.getType()))
                    valueToAdapt = PredefinedAdapterFactory.create(field.getType()).convert(valueToAdapt);
                else
                    throw new IllegalArgumentException("Object passed [" + valueToAdapt
                            + "] cannot be converted to type wanted[" + field.getType() + "] for field["
                            + field.getName() + "] in adapter[" + mappingId + "]");
            } else {
                if (!PredefinedClassTypeConverter.isPredefined(field.getType())) {
                    Class paramClazz = classLoader.loadClass(fieldName);
                    valueToAdapt = paramClazz.cast(valueToAdapt);
                }
            }
            field.set(result, valueToAdapt);
        }
    } catch (IllegalArgumentException e) {
        throw new UnableToAdaptException(
                "arg [" + valueToAdapt + "] is illegal for field with name [" + attributeName + "]", e);
    } catch (SecurityException e) {
        throw new UnableToAdaptException(e);
    } catch (IllegalAccessException e) {
        throw new UnableToAdaptException(
                "field [" + attributeName + "] does not accessible on class [" + result.getClass() + "]", e);
    } catch (NoSuchFieldException e) {
        logger.log(Level.WARNING,
                "field [" + attributeName + "] does not exist on class [" + result.getClass() + "]", e);
    } catch (ClassNotFoundException e) {
        throw new UnableToAdaptException(
                "field [" + attributeName + "] class not found [" + result.getClass() + "]", e);
    }
    return result;
}

From source file:com.github.strawberry.guice.config.ConfigLoader.java

private static Map<?, ?> mapOf(Field field, Map properties, String key) {
    Map map = mapImplementationOf(field.getType());

    Object o = properties.get(key);
    if (o instanceof Map) {
        Option<Type> valueType = genericTypeOf(field, 1);
        if (valueType.exists(isAssignableTo(Map.class)) || valueType.exists(isEqualTo(Object.class))) {
            map.put(key, o);//from   ww w  .  jav a  2  s .com
        } else {
            map.putAll((Map) o);
        }
    } else {
        map.put(key, o);
    }

    return map;
}

From source file:com.github.strawberry.guice.config.ConfigLoader.java

private static Map<?, ?> nestedMapOf(Field field, Map properties, Set<String> redisKeys) {
    Map map = mapImplementationOf(field.getType());
    for (String redisKey : redisKeys) {
        map.put(redisKey, properties.get(redisKey));
    }/* w ww. j a v  a 2 s.c  om*/
    return map;
}

From source file:com.jilk.ros.rosbridge.implementation.JSON.java

public static Class getFieldClass(Message parent, JSONObject jo, Field f, Registry<Class> r) {
    Class fc;//from w w  w .  j av  a2s  .c o  m
    fc = f.getType();
    if (fc.isArray())
        fc = f.getType().getComponentType();
    if (Indication.isIndicated(f) && (jo != null)) {
        //fc = Indication.getIndication(parent,
        //        (String) jo.get(Indication.getIndicatorName(parent.getClass())));
        fc = r.lookup(parent.getClass(), (String) jo.get(Indication.getIndicatorName(parent.getClass())));
        //System.out.println("JSON.getFieldClass: parent class " + parent.getClass().getName() +
        //        " Indicator: " + Indication.getIndicatorName(parent.getClass()) + 
        //        " result: " + fc.getName());
    }
    return fc;
}

From source file:de.micromata.genome.gwiki.utils.ClassUtils.java

public static void populateBeanWithPuplicMembers(Object bean, Map<String, Object> reqMap) {
    Class<?> cls = bean.getClass();
    for (Map.Entry<String, Object> me : reqMap.entrySet()) {
        try {/*from  w  w  w . ja  v a 2 s. c  o  m*/
            String s = getSetter(me.getKey());
            if (hasMethod(cls, s) == true) {
                BeanUtilsBean.getInstance().setProperty(bean, me.getKey(), me.getValue());
            } else {
                Field f;
                try {
                    f = cls.getField(me.getKey());
                    if (f != null) {
                        f.set(bean, convert(me.getValue(), f.getType()));
                    }
                } catch (NoSuchFieldException ex) {
                    continue;
                }
            }
        } catch (Exception ex) {
            throw new RuntimeException("Failure to set propert: " + me.getKey() + " in class: " + cls.getName()
                    + "; with value: " + me.getValue() + ";" + ex.getMessage(), ex);
        }
    }
}

From source file:gr.abiss.calipso.jpasearch.specifications.GenericSpecifications.java

protected static boolean isAcceptableSimpleSearchFieldClass(Field tmpField) {
    return tmpField.getClass().isEnum() || tmpField.getType().equals(String.class);
}

From source file:com.searchbox.core.ref.ReflectionUtils.java

public static void inspectAndSaveAttribute(Class<?> searchElement, Collection<AttributeEntity> attributes) {
    if (searchElement != null) {
        for (Field field : searchElement.getDeclaredFields()) {
            if (field.isAnnotationPresent(SearchAttribute.class)) {
                AttributeEntity attrDef = new AttributeEntity().setName(field.getName())
                        .setType(field.getType());
                String value = field.getAnnotation(SearchAttribute.class).value();
                if (value != null && !value.isEmpty()) {
                    try {
                        Object ovalue = BeanUtils.instantiateClass(field.getType().getConstructor(String.class),
                                value);/*ww w. jav  a  2  s.  co  m*/
                        attrDef.setValue(ovalue);
                    } catch (BeanInstantiationException | NoSuchMethodException | SecurityException e) {
                        LOGGER.trace("Could not construct default value (not much of a problem)", e);
                    }
                }
                attributes.add(attrDef);
            }
        }
        inspectAndSaveAttribute(searchElement.getSuperclass(), attributes);
    } else {
        return;
    }
}

From source file:eagle.log.entity.EntityQualifierUtils.java

public static byte[] toBytes(EntityDefinition ed, String qualifierName, String qualifierValueInStr) {
    // Get field type from entity class
    // and skip for not-found fields query expression
    Object typedValue = null;/*from   w  w  w  .j a  va  2  s .c om*/
    EntitySerDeser serDeser = null;
    if (ed.isTag(qualifierName)) {
        typedValue = qualifierValueInStr;
        serDeser = EntityDefinitionManager.getSerDeser(String.class);
    } else {
        try {
            Field field = ed.getEntityClass().getDeclaredField(qualifierName);
            Class<?> fieldType = field.getType();
            serDeser = EntityDefinitionManager.getSerDeser(fieldType);
            if (serDeser == null) {
                throw new IllegalArgumentException("Can't find EntitySerDeser for field: " + qualifierName
                        + "'s type: " + fieldType + ", so the field is not supported to be filtered yet");
            }
            typedValue = convertStringToObject(qualifierValueInStr, fieldType);
        } catch (NoSuchFieldException ex) {
            // Handle the field not found exception in caller
            LOG.error("Field " + qualifierName + " not found in " + ed.getEntityClass());
            throw new IllegalArgumentException(
                    "Field " + qualifierName + " not found in " + ed.getEntityClass(), ex);
        }
    }
    return serDeser.serialize(typedValue);
}