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.autobizlogic.abl.util.BeanUtil.java

protected static void setValueWithField(Field field, Object bean, Object value) {

    try {/* ww w  .  ja  v a 2  s.  co m*/
        field.setAccessible(true);
        field.set(bean, value);
    } catch (Exception ex) {
        String extraInfo = "";
        if (value != null) {
            // If the two classes have the same name, it's probably a classloader problem,
            // so we generate more informative output to help debug
            if (field.getType().getName().equals(value.getClass().getName())) {
                extraInfo = ". It looks like the two classes have the same name, so this is "
                        + "probably a classloader issue. The bean field's class comes from "
                        + field.getType().getClassLoader() + ", the bean itself comes from "
                        + bean.getClass().getClassLoader() + ", the value class comes from "
                        + value.getClass().getClassLoader();
            }
        }
        throw new RuntimeException("Unable to set property " + field.getName() + " on instance of "
                + bean.getClass().getName() + " using field " + field.getName() + extraInfo, ex);
    }
}

From source file:com.helpinput.core.Utils.java

public static boolean isFieldType(Field field, Class<?> clz) {
    if (field != null) {
        Class<?> type = field.getType();
        if (type.isAssignableFrom(clz)) {
            return true;
        }//w w w  .  j  a v a  2  s  . c  o  m
    }
    return false;
}

From source file:me.xiaopan.android.gohttp.requestobject.RequestParser.java

/**
 * ?typecollectionType?collectionType=List.classtype=Date.class??DateList
 */// w ww .  j a  v a  2  s .c  o  m
@SuppressWarnings("rawtypes")
private static boolean isCollectionByType(Field field, Class<? extends Collection> collectionType,
        Class<?> type) {
    Class<?> fieldType = field.getType();
    if (collectionType.isAssignableFrom(fieldType)) {
        Class<?> first = (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
        return type.isAssignableFrom(first);
    } else {
        return false;
    }
}

From source file:gov.nih.nci.system.web.util.RESTUtil.java

/**
 * Convert ISO attr parts into attribute names Expected formats: List< Map<
 * String, List<?> > > ? can be String or a Map<String, String>
 * [{part_0=[value, code, codeSystem, {type=[AL]}]}, {part_1=[value, code,
 * codeSystem, {type=[AL]}]}] resulting: part_0.value, part_0.code,
 * part_0.codeSystem, part_0.type, part_1.value, part_1.code,
 * part_1.codeSystem, part_1.type/*from w w  w .j  a  v a  2 s  .  c o m*/
 *
 * Expected formats: List< Map< String, List< Map< String, List<?> > > > > ?
 * can be String or a Map<String, String>
 * [{item<gov.nih.nci.iso21090.Ad>=[{part_0=[value, code, codeSystem,
 * {type=[AL]}]}, {part_1=[value, code, codeSystem, {type=[AL]}]}]}]
 * resulting: item.part_0.value, item.part_0.code, item.part_0.codeSystem,
 * item.part_0.type, item.part_1.value, item.part_1.code,
 * item.part_1.codeSystem, item.part_1.type
 *
 *
 * @param attrs
 * @return
 */
public static List<String> getSearchableIsoDataTypeFieldsWithFN(Field field, List attrs) {

    String typeName = field.getType().getName();
    log.debug("typeName: " + typeName);
    if (typeName.equals("gov.nih.nci.iso21090.Ad") || typeName.equals("gov.nih.nci.iso21090.En")
            || typeName.equals("gov.nih.nci.iso21090.EnOn") || typeName.equals("gov.nih.nci.iso21090.EnPn"))
        return getSearchableIsoDataTypeFieldsForAd(field, attrs);
    else if (typeName.equals("gov.nih.nci.iso21090.DSet"))
        return getSearchableIsoDataTypeFieldsForDsetAd(field, attrs);
    else if (typeName.equals("gov.nih.nci.iso21090.Cd"))
        return getSearchableIsoDataTypeFieldsForCd(field, attrs);
    else if (typeName.equals("gov.nih.nci.iso21090.Sc") || typeName.equals("gov.nih.nci.iso21090.Ivl"))
        return getSearchableIsoDataTypeFieldsForSc(field, attrs);

    String fieldName = field.getName();
    List<String> fnAttrs = new ArrayList();
    // List of ISO fields
    Iterator iter = attrs.iterator();
    while (iter.hasNext()) {
        Object obj = iter.next();
        if (obj instanceof java.lang.String) {
            String value = (String) obj;

            if (field.getName().equals(value))
                fnAttrs.add(value);
            else
                fnAttrs.add(field.getName() + "." + value);
            // log.debug("instanceof java.lang.String*******" +
            // obj);
        }
    }
    // log.debug("returning fnAttrs: " + fnAttrs);
    return fnAttrs;
}

From source file:gov.nih.nci.system.web.util.RESTUtil.java

/**
 * Convert ISO attr parts into attribute names Expected formats: List< Map<
 * String, List<?> > > ? can be String or a Map<String, String>
 * [{part_0=[value, code, codeSystem, {type=[AL]}]}, {part_1=[value, code,
 * codeSystem, {type=[AL]}]}] resulting: part_0.value, part_0.code,
 * part_0.codeSystem, part_0.type, part_1.value, part_1.code,
 * part_1.codeSystem, part_1.type/*from  ww w .java2  s  .c o m*/
 *
 * Expected formats: List< Map< String, List< Map< String, List<?> > > > > ?
 * can be String or a Map<String, String>
 * [{item<gov.nih.nci.iso21090.Ad>=[{part_0=[value, code, codeSystem,
 * {type=[AL]}]}, {part_1=[value, code, codeSystem, {type=[AL]}]}]}]
 * resulting: item.part_0.value, item.part_0.code, item.part_0.codeSystem,
 * item.part_0.type, item.part_1.value, item.part_1.code,
 * item.part_1.codeSystem, item.part_1.type
 *
 *
 * @param attrs
 * @return
 */
public static List<String> getSearchableIsoDataTypeFieldsForCd(Field field, List attrs) {

    String typeName = field.getType().getName();
    String fieldName = field.getName();
    List<String> fnAttrs = new ArrayList();
    // List of ISO fields
    Iterator iter = attrs.iterator();
    while (iter.hasNext()) {
        Object obj = iter.next();
        if (obj instanceof java.lang.String) {
            String value = (String) obj;

            if (field.getName().equals(value))
                fnAttrs.add(value);
            else
                fnAttrs.add(field.getName() + "." + value);
            // log.debug("instanceof java.lang.String*******" +
            // obj);
        } else if (obj instanceof java.util.Map) {
            Map valueMap = (java.util.Map) obj;
            Iterator valueIter = valueMap.keySet().iterator();
            while (valueIter.hasNext()) {
                String key = (String) valueIter.next();
                List keyValues = (java.util.List) valueMap.get(key);
                Iterator listIter = keyValues.iterator();
                while (listIter.hasNext()) {
                    String keyValueName = (String) listIter.next();
                    fnAttrs.add(field.getName() + "." + key + "." + keyValueName);
                }
            }
            // log.debug("Don't know-----------------------");
        }
    }
    // log.debug("returning fnAttrs: " + fnAttrs);
    return fnAttrs;
}

From source file:com.google.code.simplestuff.bean.SimpleBean.java

/**
 * /* ww w  .j a va  2  s .  c  om*/
 * Returns the description of a bean considering only the
 * {@link BusinessField} annotated fields.
 * 
 * @param bean The bean to describe.
 * @return The description of the bean.
 * @throws IllegalArgumentException If the bean is not a Business Object.
 */
public static String toString(Object bean) {

    if (bean == null) {
        throw new IllegalArgumentException("The bean passed is null!!!");
    }

    BusinessObjectDescriptor businessObjectInfo = BusinessObjectContext
            .getBusinessObjectDescriptor(bean.getClass());

    if (businessObjectInfo == null) {
        return bean.toString();
        // throw new IllegalArgumentException(
        // "The bean passed is not annotated in the hierarchy as Business Object!!!");
    }

    Collection<Field> annotatedField = businessObjectInfo.getAnnotatedFields();
    ToStringBuilder builder = new ToStringBuilder(bean, ToStringStyle.MULTI_LINE_STYLE);
    for (Field field : annotatedField) {
        final BusinessField fieldAnnotation = field.getAnnotation(BusinessField.class);
        if ((fieldAnnotation != null) && (fieldAnnotation.includeInToString())) {
            try {
                // Vincenzo Vitale(vita) May 23, 2007 2:39:26 PM: some
                // date implementations give not equals values...
                if ((ClassUtils.isAssignable(field.getType(), Date.class))
                        || (ClassUtils.isAssignable(field.getType(), Calendar.class))) {
                    Object fieldValue = PropertyUtils.getProperty(bean, field.getName());
                    if (fieldValue != null) {
                        builder.append(DateUtils.round(fieldValue, Calendar.SECOND));
                    }

                } else {
                    builder.append(PropertyUtils.getProperty(bean, field.getName()));
                }
            } catch (IllegalAccessException e) {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "IllegalAccessException exception when calculating the string representation of class"
                                    + bean.getClass().toString(),
                            e);
                }
            } catch (InvocationTargetException e) {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "InvocationTargetException exception when calculating the string representation of class"
                                    + bean.getClass().toString(),
                            e);
                }
            } catch (NoSuchMethodException e) {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "NoSuchMethodException exception when calculating the string representation of a bean of class"
                                    + bean.getClass().toString(),
                            e);
                }
            }
        }
    }

    return builder.toString();

}

From source file:cross.applicationContext.ReflectionApplicationContextGenerator.java

/**
 *
 * @param field//from  ww w . j ava 2  s  . c o  m
 * @return
 */
public static Class<?> getGenericFieldType(Field field) {
    Type fieldType = field.getGenericType();
    if (fieldType instanceof ParameterizedType) {
        Type[] t = ((ParameterizedType) fieldType).getActualTypeArguments();
        if (t != null) {
            return (Class<?>) t[0];
        }
    }
    return field.getType();
}

From source file:com.android.camera2.its.ItsSerializer.java

@SuppressWarnings("unchecked")
public static CaptureRequest.Builder deserialize(CaptureRequest.Builder mdDefault, JSONObject jsonReq)
        throws ItsException {
    try {//w  ww.ja  v a  2  s.  com
        Logt.i(TAG, "Parsing JSON capture request ...");

        // Iterate over the CaptureRequest reflected fields.
        CaptureRequest.Builder md = mdDefault;
        Field[] allFields = CaptureRequest.class.getDeclaredFields();
        for (Field field : allFields) {
            if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())
                    && field.getType() == CaptureRequest.Key.class
                    && field.getGenericType() instanceof ParameterizedType) {
                ParameterizedType paramType = (ParameterizedType) field.getGenericType();
                Type[] argTypes = paramType.getActualTypeArguments();
                if (argTypes.length > 0) {
                    CaptureRequest.Key key = (CaptureRequest.Key) field.get(md);
                    String keyName = key.getName();
                    Type keyType = argTypes[0];

                    // For each reflected CaptureRequest entry, look inside the JSON object
                    // to see if it is being set. If it is found, remove the key from the
                    // JSON object. After this process, there should be no keys left in the
                    // JSON (otherwise an invalid key was specified).

                    if (jsonReq.has(keyName) && !jsonReq.isNull(keyName)) {
                        if (keyType instanceof GenericArrayType) {
                            Type elmtType = ((GenericArrayType) keyType).getGenericComponentType();
                            JSONArray ja = jsonReq.getJSONArray(keyName);
                            Object val[] = new Object[ja.length()];
                            for (int i = 0; i < ja.length(); i++) {
                                if (elmtType == int.class) {
                                    Array.set(val, i, ja.getInt(i));
                                } else if (elmtType == byte.class) {
                                    Array.set(val, i, (byte) ja.getInt(i));
                                } else if (elmtType == float.class) {
                                    Array.set(val, i, (float) ja.getDouble(i));
                                } else if (elmtType == long.class) {
                                    Array.set(val, i, ja.getLong(i));
                                } else if (elmtType == double.class) {
                                    Array.set(val, i, ja.getDouble(i));
                                } else if (elmtType == boolean.class) {
                                    Array.set(val, i, ja.getBoolean(i));
                                } else if (elmtType == String.class) {
                                    Array.set(val, i, ja.getString(i));
                                } else if (elmtType == Size.class) {
                                    JSONObject obj = ja.getJSONObject(i);
                                    Array.set(val, i, new Size(obj.getInt("width"), obj.getInt("height")));
                                } else if (elmtType == Rect.class) {
                                    JSONObject obj = ja.getJSONObject(i);
                                    Array.set(val, i, new Rect(obj.getInt("left"), obj.getInt("top"),
                                            obj.getInt("bottom"), obj.getInt("right")));
                                } else if (elmtType == Rational.class) {
                                    JSONObject obj = ja.getJSONObject(i);
                                    Array.set(val, i,
                                            new Rational(obj.getInt("numerator"), obj.getInt("denominator")));
                                } else if (elmtType == RggbChannelVector.class) {
                                    JSONArray arr = ja.getJSONArray(i);
                                    Array.set(val, i,
                                            new RggbChannelVector((float) arr.getDouble(0),
                                                    (float) arr.getDouble(1), (float) arr.getDouble(2),
                                                    (float) arr.getDouble(3)));
                                } else if (elmtType == ColorSpaceTransform.class) {
                                    JSONArray arr = ja.getJSONArray(i);
                                    Rational xform[] = new Rational[9];
                                    for (int j = 0; j < 9; j++) {
                                        xform[j] = new Rational(arr.getJSONObject(j).getInt("numerator"),
                                                arr.getJSONObject(j).getInt("denominator"));
                                    }
                                    Array.set(val, i, new ColorSpaceTransform(xform));
                                } else if (elmtType == MeteringRectangle.class) {
                                    JSONObject obj = ja.getJSONObject(i);
                                    Array.set(val, i, new MeteringRectangle(obj.getInt("x"), obj.getInt("y"),
                                            obj.getInt("width"), obj.getInt("height"), obj.getInt("weight")));
                                } else {
                                    throw new ItsException("Failed to parse key from JSON: " + keyName);
                                }
                            }
                            if (val != null) {
                                Logt.i(TAG, "Set: " + keyName + " -> " + Arrays.toString(val));
                                md.set(key, val);
                                jsonReq.remove(keyName);
                            }
                        } else {
                            Object val = null;
                            if (keyType == Integer.class) {
                                val = jsonReq.getInt(keyName);
                            } else if (keyType == Byte.class) {
                                val = (byte) jsonReq.getInt(keyName);
                            } else if (keyType == Double.class) {
                                val = jsonReq.getDouble(keyName);
                            } else if (keyType == Long.class) {
                                val = jsonReq.getLong(keyName);
                            } else if (keyType == Float.class) {
                                val = (float) jsonReq.getDouble(keyName);
                            } else if (keyType == Boolean.class) {
                                val = jsonReq.getBoolean(keyName);
                            } else if (keyType == String.class) {
                                val = jsonReq.getString(keyName);
                            } else if (keyType == Size.class) {
                                JSONObject obj = jsonReq.getJSONObject(keyName);
                                val = new Size(obj.getInt("width"), obj.getInt("height"));
                            } else if (keyType == Rect.class) {
                                JSONObject obj = jsonReq.getJSONObject(keyName);
                                val = new Rect(obj.getInt("left"), obj.getInt("top"), obj.getInt("right"),
                                        obj.getInt("bottom"));
                            } else if (keyType == Rational.class) {
                                JSONObject obj = jsonReq.getJSONObject(keyName);
                                val = new Rational(obj.getInt("numerator"), obj.getInt("denominator"));
                            } else if (keyType == RggbChannelVector.class) {
                                JSONObject obj = jsonReq.optJSONObject(keyName);
                                JSONArray arr = jsonReq.optJSONArray(keyName);
                                if (arr != null) {
                                    val = new RggbChannelVector((float) arr.getDouble(0),
                                            (float) arr.getDouble(1), (float) arr.getDouble(2),
                                            (float) arr.getDouble(3));
                                } else if (obj != null) {
                                    val = new RggbChannelVector((float) obj.getDouble("red"),
                                            (float) obj.getDouble("greenEven"),
                                            (float) obj.getDouble("greenOdd"), (float) obj.getDouble("blue"));
                                } else {
                                    throw new ItsException("Invalid RggbChannelVector object");
                                }
                            } else if (keyType == ColorSpaceTransform.class) {
                                JSONArray arr = jsonReq.getJSONArray(keyName);
                                Rational a[] = new Rational[9];
                                for (int i = 0; i < 9; i++) {
                                    a[i] = new Rational(arr.getJSONObject(i).getInt("numerator"),
                                            arr.getJSONObject(i).getInt("denominator"));
                                }
                                val = new ColorSpaceTransform(a);
                            } else if (keyType instanceof ParameterizedType
                                    && ((ParameterizedType) keyType).getRawType() == Range.class
                                    && ((ParameterizedType) keyType).getActualTypeArguments().length == 1
                                    && ((ParameterizedType) keyType)
                                            .getActualTypeArguments()[0] == Integer.class) {
                                JSONArray arr = jsonReq.getJSONArray(keyName);
                                val = new Range<Integer>(arr.getInt(0), arr.getInt(1));
                            } else {
                                throw new ItsException(
                                        "Failed to parse key from JSON: " + keyName + ", " + keyType);
                            }
                            if (val != null) {
                                Logt.i(TAG, "Set: " + keyName + " -> " + val);
                                md.set(key, val);
                                jsonReq.remove(keyName);
                            }
                        }
                    }
                }
            }
        }

        // Ensure that there were no invalid keys in the JSON request object.
        if (jsonReq.length() != 0) {
            throw new ItsException("Invalid JSON key(s): " + jsonReq.toString());
        }

        Logt.i(TAG, "Parsing JSON capture request completed");
        return md;
    } catch (java.lang.IllegalAccessException e) {
        throw new ItsException("Access error: ", e);
    } catch (org.json.JSONException e) {
        throw new ItsException("JSON error: ", e);
    }
}

From source file:com.bosscs.spark.commons.utils.Utils.java

/**
 * Returns an instance clone./*from w w w .  j av a 2s .  com*/
 * this method gets every class property by reflection, including its parents properties
 * @param t
 * @param <T>
 * @return T object.
 */
public static <T> T cloneObjectWithParents(T t) throws IllegalAccessException, InstantiationException {
    T clone = (T) t.getClass().newInstance();

    List<Field> allFields = new ArrayList<>();

    Class parentClass = t.getClass().getSuperclass();

    while (parentClass != null) {
        Collections.addAll(allFields, parentClass.getDeclaredFields());
        parentClass = parentClass.getSuperclass();
    }

    Collections.addAll(allFields, t.getClass().getDeclaredFields());

    for (Field field : allFields) {
        int modifiers = field.getModifiers();
        //We skip final and static fields
        if ((Modifier.FINAL & modifiers) != 0 || (Modifier.STATIC & modifiers) != 0) {
            continue;
        }
        field.setAccessible(true);

        Object value = field.get(t);

        if (Collection.class.isAssignableFrom(field.getType())) {
            Collection collection = (Collection) field.get(clone);
            if (collection == null) {
                collection = (Collection) field.get(t).getClass().newInstance();
            }
            collection.addAll((Collection) field.get(t));
            value = collection;
        } else if (Map.class.isAssignableFrom(field.getType())) {
            Map clonMap = (Map) field.get(t).getClass().newInstance();
            clonMap.putAll((Map) field.get(t));
            value = clonMap;
        }
        field.set(clone, value);
    }

    return clone;
}

From source file:com.gatf.executor.core.AcceptanceTestContext.java

public static Map<String, String> getHttpHeadersMap() throws Exception {
    Map<String, String> headers = new HashMap<String, String>();
    Field[] declaredFields = HttpHeaders.class.getDeclaredFields();
    for (Field field : declaredFields) {
        if (java.lang.reflect.Modifier.isStatic(field.getModifiers()) && field.getType().equals(String.class)) {
            headers.put(field.get(null).toString().toLowerCase(), field.get(null).toString());
        }/* ww  w  .j ava2s  .  c om*/
    }
    return headers;
}