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.trafficspaces.api.model.Resource.java

public void setJSONObject(JSONObject jsonObject) {
    Iterator itr = jsonObject.keys();
    while (itr.hasNext()) {
        String key = (String) itr.next();
        Object value = jsonObject.opt(key);

        try {//  w  ww.ja  v  a 2 s .  c  om
            Field field = this.getClass().getField(key);
            Class type = field.getType();

            int fieldModifiers = field.getModifiers();
            //System.out.println("key=" + key + ", name=" + field.getName() + ", value=" + value + ", type=" +type + ", componentType=" +type.getComponentType() + 
            //      ", ispublic="+Modifier.isPublic(fieldModifiers) + ", isstatic="+Modifier.isStatic(fieldModifiers) + ", isnative="+Modifier.isNative(fieldModifiers) +
            //      ", isprimitive="+type.isPrimitive() + ", isarray="+type.isArray() + ", isResource="+Resource.class.isAssignableFrom(type));

            if (type.isPrimitive()) {
                if (type.equals(int.class)) {
                    field.setInt(this, jsonObject.getInt(key));
                } else if (type.equals(double.class)) {
                    field.setDouble(this, jsonObject.getDouble(key));
                }
            } else if (type.isArray()) {
                JSONArray jsonArray = null;
                if (value instanceof JSONArray) {
                    jsonArray = (JSONArray) value;
                } else if (value instanceof JSONObject) {
                    JSONObject jsonSubObject = (JSONObject) value;
                    jsonArray = jsonSubObject.optJSONArray(key.substring(0, key.length() - 1));
                }
                if (jsonArray != null && jsonArray.length() > 0) {
                    Class componentType = type.getComponentType();
                    Object[] values = (Object[]) Array.newInstance(componentType, jsonArray.length());
                    for (int j = 0; j < jsonArray.length(); j++) {
                        Resource resource = (Resource) componentType.newInstance();
                        resource.setJSONObject(jsonArray.getJSONObject(j));
                        values[j] = resource;
                    }
                    field.set(this, values);
                }
            } else if (Resource.class.isAssignableFrom(type) && value instanceof JSONObject) {
                Resource resource = (Resource) type.newInstance();
                resource.setJSONObject((JSONObject) value);
                field.set(this, resource);
            } else if (type.equals(String.class) && value instanceof String) {
                field.set(this, (String) value);
            }
        } catch (NoSuchFieldException nsfe) {
            System.err.println("warning: field does not exist. key=" + key + ",value=" + value);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("error: key=" + key + ",value=" + value + ", error=" + e.getMessage());
        }
    }
}

From source file:gov.nih.nci.cabig.ctms.audit.dao.AuditHistoryRepository.java

@SuppressWarnings("unchecked")
public List<AuditHistory> getAuditDetailsForEntity(final Class entityClass, final Integer entityId,
        final Calendar calendar)

{
    final List<gov.nih.nci.cabig.ctms.audit.domain.DataAuditEvent> dataAuditEvents = getDataAuditEvents(
            entityClass, entityId, calendar);

    final List<AuditHistory> auditHistories = new ArrayList<AuditHistory>();

    Field[] fields = entityClass.getDeclaredFields();
    List<String> attributeFieldsName = new ArrayList<String>();

    for (Field field : fields) {
        if (field.getType().isPrimitive() || field.getType().isInstance("")
                || field.getType().isInstance(new Date())) {
            attributeFieldsName.add(field.getName());

        }/*from  ww w  . j a v a2s  .  c o  m*/
    }
    for (DataAuditEvent auditEvent : dataAuditEvents) {

        AuditHistory auditHistory = createAuditHistory(auditEvent);
        List<String> attributeFields = new ArrayList<String>();
        attributeFields.addAll(attributeFieldsName);
        List<AuditHistoryDetail> auditHistoryDetails = getEventValues(attributeFields, auditEvent);
        auditHistory.addValues(auditHistoryDetails);
        auditHistories.add(auditHistory);

    }
    return auditHistories;

}

From source file:net.mindengine.blogix.db.readers.ObjectReader.java

private Object convertFieldValue(String fieldValue, Field field) {
    if (fieldValue == null) {
        return null;
    }/*from  www . j  a va 2  s  . c  o m*/
    Class<?> type = field.getType();
    try {
        return convertStringValueToType(fieldValue, type);
    } catch (Exception e) {
        throw new IllegalArgumentException("Cannot convert value '" + StringUtils.abbreviate(fieldValue, 20)
                + "' to field " + field.toString(), e);
    }
}

From source file:de.micromata.genome.util.bean.PrivateBeanUtils.java

/**
 * Find getter from field.//from w  w  w.  ja  v a  2s.  c om
 *
 * @param clazz the clazz
 * @param field the field
 * @return the method
 */
public static Method findGetterFromField(Class<?> clazz, Field field) {
    return findGetterFromField(clazz, field.getName(), field.getType());
}

From source file:com.grandhunterman.dnvm.common.Message.java

@Override
public final void fromBytes(ByteBuf buf) {
    try {//  w ww  .ja va  2 s.  c  o  m
        Class<?> clazz = getClass();
        for (Field f : clazz.getDeclaredFields()) {
            Class<?> type = f.getType();
            if (acceptField(f, type))
                readField(f, type, buf);
        }
    } catch (Exception e) {
        throw new RuntimeException("Error at reading packet " + this, e);
    }
}

From source file:com.grandhunterman.dnvm.common.Message.java

@Override
public final void toBytes(ByteBuf buf) {
    try {//from  ww  w .j  ava 2s  . c  om
        Class<?> clazz = getClass();
        for (Field f : clazz.getDeclaredFields()) {
            Class<?> type = f.getType();
            if (acceptField(f, type))
                writeField(f, type, buf);
        }
    } catch (Exception e) {
        throw new RuntimeException("Error at writing packet " + this, e);
    }
}

From source file:com.khubla.cbean.serializer.impl.json.JSONArrayFieldSerializer.java

@Override
public void deserialize(Object o, Field field, String value) throws SerializerException {
    try {//from  w w  w .j  a v  a2s .  c o m
        final JSONArray jsonArray = new JSONArray(value);
        final Object od = Array.newInstance(field.getType().getComponentType(), jsonArray.length());
        PropertyUtils.setProperty(o, field.getName(), od);
        final Class<?> componentType = field.getType().getComponentType();
        if (componentType.isPrimitive()) {
            for (int i = 0; i < jsonArray.length(); i++) {
                final String v = jsonArray.getString(i);
                PropertyUtils.setIndexedProperty(o, field.getName(), i,
                        ConvertUtils.convert(v, field.getType().getComponentType()));
            }
        } else {
            final CBean<Object> cBean = CBeanServer.getInstance().getCBean(componentType);
            for (int i = 0; i < jsonArray.length(); i++) {
                final Object co = cBean.load(new CBeanKey(jsonArray.getString(i)));
                PropertyUtils.setIndexedProperty(o, field.getName(), i,
                        ConvertUtils.convert(co, field.getType().getComponentType()));
            }
        }
    } catch (final Exception e) {
        throw new SerializerException(e);
    }
}

From source file:de.ks.flatadocdb.defaults.ReflectionLuceneDocumentExtractor.java

protected DocField createDocField(Field f) {
    try {/*from   www.jav a2s. co m*/
        Class<?> type = f.getType();
        f.setAccessible(true);
        MethodHandle getter = MethodHandles.lookup().unreflectGetter(f);

        if (TypeUtils.isArrayType(type)) {
            return createArrayDocField(f, getter);
        } else if (Collection.class.isAssignableFrom(type)) {
            return createCollectionDocField(f, getter);
        } else if (String.class.equals(type)) {
            return createStringDocField(f, getter);
        } else if (LocalDateTime.class.equals(type)) {
            return createLocalDateTimeDocField(f, getter);
        } else {
            return new DocField(f, getter, (id, value) -> new StringField(id, String.valueOf(value),
                    org.apache.lucene.document.Field.Store.YES));
        }
    } catch (Exception e) {
        log.error("Could not extract docfield from {}", f, e);
        throw new RuntimeException(e);
    }
}

From source file:nl.surfnet.coin.teams.control.AbstractControllerTest.java

private boolean doAutoWireMock(Object target, Object mock, Class interfaceClass, Field[] fields)
        throws IllegalAccessException {
    boolean found = false;
    for (Field field : fields) {
        if (field.getType().equals(interfaceClass)) {
            ReflectionUtils.makeAccessible(field);
            field.set(target, mock);/*w w  w  .  j av a  2  s.  c  o m*/
            found = true;
            break;
        }
    }
    return found;
}