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.tugo.dt.PojoUtils.java

private static String getSingleFieldSetterExpression(final Class<?> pojoClass, final String fieldExpression,
        final Class<?> exprClass) {
    JavaStatement code = new JavaStatement(
            pojoClass.getName().length() + fieldExpression.length() + exprClass.getName().length() + 32);
    /* Construct ((<pojo class name>)pojo). */
    code.appendCastToTypeExpr(pojoClass, OBJECT).append(".");
    try {// w  w  w .j a va  2  s .c  o m
        final Field field = pojoClass.getField(fieldExpression);
        if (ClassUtils.isAssignable(exprClass, field.getType())) {
            /* there is public field on the class, use direct assignment. */
            /* append <field name> = (<field type>)val; */
            return code.append(field.getName()).append(" = ").appendCastToTypeExpr(exprClass, VAL)
                    .getStatement();
        }
        logger.debug("{} can not be assigned to {}. Proceeding to locate a setter method.", exprClass, field);
    } catch (NoSuchFieldException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a setter method.", pojoClass,
                fieldExpression);
    } catch (SecurityException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a setter method.", pojoClass,
                fieldExpression);
    }

    final String setMethodName = SET + upperCaseWord(fieldExpression);
    Method bestMatchMethod = null;
    List<Method> candidates = new ArrayList<Method>();
    for (Method method : pojoClass.getMethods()) {
        if (setMethodName.equals(method.getName())) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length == 1) {
                if (exprClass == parameterTypes[0]) {
                    bestMatchMethod = method;
                    break;
                } else if (org.apache.commons.lang.ClassUtils.isAssignable(exprClass, parameterTypes[0])) {
                    candidates.add(method);
                }
            }
        }
    }

    if (bestMatchMethod == null) { // We did not find the exact match, use candidates to find the match
        if (candidates.size() == 0) {
            logger.debug("{} does not have suitable setter method {}. Returning original expression {}.",
                    pojoClass, setMethodName, fieldExpression);
            /* We did not find any match at all, use original expression */
            /* append = (<expr type>)val;*/
            return code.append(fieldExpression).append(" = ").appendCastToTypeExpr(exprClass, VAL)
                    .getStatement();
        } else {
            // TODO: see if we can find a better match
            bestMatchMethod = candidates.get(0);
        }
    }

    /* We found a method that we may use for setter */
    /* append <method name>((<expr class)val); */
    return code.append(bestMatchMethod.getName()).append("(").appendCastToTypeExpr(exprClass, VAL).append(")")
            .getStatement();
}

From source file:eu.crisis_economics.abm.model.ModelUtils.java

/**
  * A depth first recursive parameter search tool. This function accepts an object
  * {@code X}, the ({@link String}) name {@code N} of a method, and a {@link Class} array
  * of method argument types. Any object in the configuration hierarchy of {@code X} which
  * has a method with with the appropriate signature and arguments is found and
  * returned.<br>/*from   www  . j  ava 2 s . c  o  m*/
  * 
  * This search operates as follows:
  * 
  * <ul>
  *   <li> If {@code X} contains a method {@code N} with the specified arguments, then 
  *        store and remember this method;
  *   <li> Otherwise search the subclasses of {@code X} for a method {@code N} with
  *        the specified arguments. If such a method is found, then store and
  *        remember this method;
  *   <li> Apply the above steps recursively (depth first) to every field in {@code X}
  *        of type {@link ComponentConfiguration}. Remember all of the methods identified
  *        by this search process and return these methods as well as the object 
  *        instances in which they were found.
  * </ul>
  * 
  * @param on
  *        The object to search.
  * @param methodToFind
  *        The method name to search for.
  * @param arguments
  *        A list of {@link Class} argument types for the method to find.
  * @return
  *        A {@link List} of {@link Pair}{@code s}. Each entry in this list is a {@link Pair}
  *        composed of one {@link Method} object and one {@link Object}. The {@link Method}
  *        satisfies the parameters of the query. The {@link Object} is an instance of an
  *        object whose class possesses the {@link Method}.
  */
public static List<Pair<Method, Object>> search(final Object on, final String methodToFind,
        final Class<?>[] arguments) {
    final List<Pair<Method, Object>> result = new ArrayList<Pair<Method, Object>>();
    final Class<?> parentType = on.getClass();
    for (Class<?> typeToSearch = parentType; typeToSearch != null; typeToSearch = typeToSearch
            .getSuperclass()) {
        Method methodPtr = null;
        try {
            // Try to find a method with the specified name and exact argument types:
            methodPtr = typeToSearch.getDeclaredMethod(methodToFind, arguments);
            result.add(Pair.create(methodPtr, on));
            continue;
        } catch (final NoSuchMethodException e) {
            // Try to downcast method arguments for other class methods with the correct name:
            final Method[] allCalleeMethods = typeToSearch.getDeclaredMethods();
            for (final Method method : allCalleeMethods) {
                if (!method.getName().equals(methodToFind))
                    continue;
                final Type[] argTypes = method.getGenericParameterTypes();
                if (argTypes.length != arguments.length)
                    continue;
                for (int j = 0; j < arguments.length; ++j) {
                    if (!arguments[j].isAssignableFrom(argTypes[j].getClass()))
                        continue;
                }
                methodPtr = method;
                result.add(Pair.create(methodPtr, on));
                continue;
            }
        }
        if (methodPtr == null)
            continue;
    }
    // Search for any ComponentConfiguration fields in the specified object:
    for (Class<?> typeToSearch = parentType; typeToSearch != null; typeToSearch = typeToSearch
            .getSuperclass()) {
        for (Field field : typeToSearch.getDeclaredFields()) {
            if (!ComponentConfiguration.class.isAssignableFrom(field.getType()))
                continue;
            field.setAccessible(true);
            final Object instance;
            try {
                instance = field.get(on);
            } catch (final IllegalArgumentException e) {
                continue; // Not found
            } catch (final IllegalAccessException e) {
                continue; // Not found
            }
            if (instance != null) {
                final List<Pair<Method, Object>> subResult = search(instance, methodToFind, arguments); // Descend into fields
                if (subResult != null && !subResult.isEmpty())
                    result.addAll(subResult);
                else
                    continue;
            }
        }
    }
    return result;
}

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

@SuppressWarnings("unchecked")
public static JSONObject serialize(CameraMetadata md) throws ItsException {
    JSONObject jsonObj = new JSONObject();
    Field[] allFields = md.getClass().getDeclaredFields();
    if (md.getClass() == TotalCaptureResult.class) {
        allFields = CaptureResult.class.getDeclaredFields();
    }/*  w  w w .ja  v  a  2s  .co  m*/
    for (Field field : allFields) {
        if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())
                && (field.getType() == CaptureRequest.Key.class || field.getType() == CaptureResult.Key.class
                        || field.getType() == TotalCaptureResult.Key.class
                        || field.getType() == CameraCharacteristics.Key.class)
                && field.getGenericType() instanceof ParameterizedType) {
            ParameterizedType paramType = (ParameterizedType) field.getGenericType();
            Type[] argTypes = paramType.getActualTypeArguments();
            if (argTypes.length > 0) {
                try {
                    Type keyType = argTypes[0];
                    Object keyObj = field.get(md);
                    MetadataEntry entry;
                    if (keyType instanceof GenericArrayType) {
                        entry = serializeArrayEntry(keyType, keyObj, md);
                    } else {
                        entry = serializeEntry(keyType, keyObj, md);
                    }

                    // TODO: Figure this weird case out.
                    // There is a weird case where the entry is non-null but the toString
                    // of the entry is null, and if this happens, the null-ness spreads like
                    // a virus and makes the whole JSON object null from the top level down.
                    // Not sure if it's a bug in the library or I'm just not using it right.
                    // Workaround by checking for this case explicitly and not adding the
                    // value to the jsonObj when it is detected.
                    if (entry != null && entry.key != null && entry.value != null
                            && entry.value.toString() == null) {
                        Logt.w(TAG, "Error encountered serializing value for key: " + entry.key);
                    } else if (entry != null) {
                        jsonObj.put(entry.key, entry.value);
                    } else {
                        // Ignore.
                    }
                } catch (IllegalAccessException e) {
                    throw new ItsException("Access error for field: " + field + ": ", e);
                } catch (org.json.JSONException e) {
                    throw new ItsException("JSON error for field: " + field + ": ", e);
                }
            }
        }
    }
    return jsonObj;
}

From source file:net.buffalo.protocal.util.ClassUtil.java

public static void setFieldValue(Object obj, String property, Object value) {
    Class type = obj.getClass();/*from w w  w .  ja v a  2 s  . c  o m*/
    Field field = null;
    ClassFieldNamePair pair = new ClassFieldNamePair(type, property);
    if (fieldCache.get(pair) == null) {
        field = (Field) getFieldMap(type).get(property);
        if (field != null) {
            fieldCache.put(pair, field);
        } else {
            throw new AccessFieldException("Cannot find field [" + property + "] for " + type);
        }
    } else {
        field = (Field) fieldCache.get(pair);
    }

    try {
        try {
            field.set(obj, value);
        } catch (IllegalArgumentException ex) {
            field.set(obj, convertValue(value, field.getType()));
        }
    } catch (SecurityException e) {
        throw new net.buffalo.protocal.AccessFieldException(e);
    } catch (IllegalAccessException e) {
        throw new net.buffalo.protocal.AccessFieldException(e);
    }
}

From source file:com.frand.easyandroid.db.sql.FFSqlBuilder.java

public static FFArrayList getFieldsAndValue(Object entity)
        throws FFDBException, IllegalArgumentException, IllegalAccessException {
    FFArrayList arrayList = new FFArrayList();
    if (entity == null) {
        throw new FFDBException("?");
    }//www .j ava 2  s .  c  o  m
    Class<?> clazz = entity.getClass();
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        if (!FFDBUtils.isTransient(field) && FFFieldUtil.isBaseDateType(field)) {
            FFPrimaryKey annotation = field.getAnnotation(FFPrimaryKey.class);
            if (annotation != null && annotation.autoIncrement()) {
            } else {
                String columnName = FFDBUtils.getColumnByField(field);
                field.setAccessible(true);
                if (columnName == null || columnName.equals("")) {
                    columnName = field.getName();
                }
                String value = "";
                if (field.getType().equals(Date.class)) {
                    value = field.get(entity) != null ? FFDBUtils.dateToString((Date) field.get(entity)) : "";
                } else {
                    value = field.get(entity) != null ? field.get(entity).toString() : "";
                }
                arrayList.add(columnName, value);
            }
        }
    }
    return arrayList;
}

From source file:com.autobizlogic.abl.util.BeanUtil.java

private static Field getFieldFromClass(Class<?> cls, String fieldName, Class<?> argClass,
        boolean onlyProtectedAndHigher) {
    Field[] allFields = cls.getDeclaredFields();
    for (Field field : allFields) {
        if (!field.getName().equals(fieldName))
            continue;
        int modifiers = field.getModifiers();
        if (onlyProtectedAndHigher && Modifier.isPrivate(modifiers))
            continue;
        if (argClass != null) {
            Class<?> genericType = getGenericType(field.getType());
            if (!genericType.isAssignableFrom(argClass)) {
                String extraInfo = "";
                // 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(argClass.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 other class comes from "
                            + argClass.getClassLoader();
                }//from  w  ww .j  a v  a 2  s  .com
                throw new RuntimeException("Bean field " + fieldName + " of class " + cls.getName()
                        + " is of the wrong type (" + field.getType().getName() + ") for the given argument, "
                        + "which is of type " + argClass.getName() + extraInfo);
            }
        }

        return field;
    }

    return null;
}

From source file:com.smart.utils.ReflectionUtils.java

/**
 * set/*from  w  w  w . j  a va 2s  .com*/
 * 
 * @param bean
 * @param fieldName
 * @param setValue
 */

public static void setValueBySetMethod(Object bean, String fieldName, Object setValue) {
    if (bean == null || fieldName == null || "".equals(fieldName))
        return;
    Field field = getDeclaredField(bean, fieldName);
    if (field == null)
        throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + bean + "]");
    Method setMethod = getDeclaredMethod(bean, getSetMethodName(fieldName), new Class<?>[] { field.getType() });
    if (setMethod != null) {
        try {
            setMethod.invoke(bean, setValue);
        } catch (Exception e) {
            logger.error("error methodName=" + setMethod.getName() + " " + e.getMessage(), e);
        }
    }

}

From source file:de.escalon.hypermedia.spring.uber.UberUtils.java

/**
 * Recursively converts object to nodes of uber data.
 *
 * @param objectNode/*from ww  w. java  2 s .c  o m*/
 *         to append to
 * @param object
 *         to convert
 */
public static void toUberData(AbstractUberNode objectNode, Object object) {
    Set<String> filtered = FILTER_RESOURCE_SUPPORT;
    if (object == null) {
        return;
    }

    try {
        // TODO: move all returns to else branch of property descriptor handling
        if (object instanceof Resource) {
            Resource<?> resource = (Resource<?>) object;
            objectNode.addLinks(resource.getLinks());
            toUberData(objectNode, resource.getContent());
            return;
        } else if (object instanceof Resources) {
            Resources<?> resources = (Resources<?>) object;

            // TODO set name using EVO see HypermediaSupportBeanDefinitionRegistrar

            objectNode.addLinks(resources.getLinks());

            Collection<?> content = resources.getContent();
            toUberData(objectNode, content);
            return;
        } else if (object instanceof ResourceSupport) {
            ResourceSupport resource = (ResourceSupport) object;

            objectNode.addLinks(resource.getLinks());

            // wrap object attributes below to avoid endless loop

        } else if (object instanceof Collection) {
            Collection<?> collection = (Collection<?>) object;
            for (Object item : collection) {
                // TODO name must be repeated for each collection item
                UberNode itemNode = new UberNode();
                objectNode.addData(itemNode);
                toUberData(itemNode, item);
            }
            return;
        }
        if (object instanceof Map) {
            Map<?, ?> map = (Map<?, ?>) object;
            for (Entry<?, ?> entry : map.entrySet()) {
                String key = entry.getKey().toString();
                Object content = entry.getValue();
                Object value = getContentAsScalarValue(content);
                UberNode entryNode = new UberNode();
                objectNode.addData(entryNode);
                entryNode.setName(key);
                if (value != null) {
                    entryNode.setValue(value);
                } else {
                    toUberData(entryNode, content);
                }
            }
        } else {
            Map<String, PropertyDescriptor> propertyDescriptors = PropertyUtils.getPropertyDescriptors(object);
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors.values()) {
                String name = propertyDescriptor.getName();
                if (filtered.contains(name)) {
                    continue;
                }
                UberNode propertyNode = new UberNode();
                Object content = propertyDescriptor.getReadMethod().invoke(object);

                if (isEmptyCollectionOrMap(content, propertyDescriptor.getPropertyType())) {
                    continue;
                }

                Object value = getContentAsScalarValue(content);
                propertyNode.setName(name);
                objectNode.addData(propertyNode);
                if (value != null) {
                    // for each scalar property of a simple bean, add valuepair nodes to data
                    propertyNode.setValue(value);
                } else {
                    toUberData(propertyNode, content);
                }
            }

            Field[] fields = object.getClass().getFields();
            for (Field field : fields) {
                String name = field.getName();
                if (!propertyDescriptors.containsKey(name)) {
                    Object content = field.get(object);
                    Class<?> type = field.getType();
                    if (isEmptyCollectionOrMap(content, type)) {
                        continue;
                    }
                    UberNode propertyNode = new UberNode();

                    Object value = getContentAsScalarValue(content);
                    propertyNode.setName(name);
                    objectNode.addData(propertyNode);
                    if (value != null) {
                        // for each scalar property of a simple bean, add valuepair nodes to data
                        propertyNode.setValue(value);
                    } else {
                        toUberData(propertyNode, content);
                    }

                }
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException("failed to transform object " + object, ex);
    }
}

From source file:com.fengduo.bee.commons.core.lang.BeanUtils.java

/**
 * ?Beanmap,map//from  w  ww.j  av  a 2  s. com
 * 
 * @param bean
 * @return
 */
public static Map<String, String> getFieldValueMap(Object bean) {
    Class<?> cls = bean.getClass();
    Map<String, String> valueMap = new LinkedHashMap<String, String>();
    LinkedList<Field> fields = _getAllFields(new LinkedList<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.formatFullDate((Date) fieldVal);
                } else {
                    result = String.valueOf(fieldVal);
                }
            }
            valueMap.put(field.getName(), result == null ? StringUtils.EMPTY : result);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            continue;
        }
    }
    return valueMap;
}

From source file:com.erudika.para.core.ParaObjectUtils.java

/**
 * Returns a map of annotated fields of a domain object. Only annotated fields are returned. This method forms the
 * basis of an Object/Grid Mapper. It converts an object to a map of key/value pairs. That map can later be
 * persisted to a data store.//  w  w  w .ja  va2 s.  c om
 * <br>
 * If {@code convertNestedToJsonString} is true all field values that are objects (i.e. not primitive types or
 * wrappers) are converted to a JSON string otherwise they are left as they are and will be serialized as regular
 * JSON objects later (structure is preserved). Null is considered a primitive type. Transient fields and
 * serialVersionUID are skipped.
 *
 * @param <P> the object type
 * @param pojo the object to convert to a map
 * @param filter a filter annotation. fields that have it will be skipped
 * @param convertNestedToJsonString true if you want to flatten the nested objects to a JSON string.
 * @return a map of fields and their values
 */
public static <P extends ParaObject> Map<String, Object> getAnnotatedFields(P pojo,
        Class<? extends Annotation> filter, boolean convertNestedToJsonString) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    if (pojo == null) {
        return map;
    }
    try {
        List<Field> fields = getAllDeclaredFields(pojo.getClass());
        // filter transient fields and those without annotations
        for (Field field : fields) {
            boolean dontSkip = ((filter == null) ? true : !field.isAnnotationPresent(filter));
            if (field.isAnnotationPresent(Stored.class) && dontSkip) {
                String name = field.getName();
                Object value = PropertyUtils.getProperty(pojo, name);
                if (!Utils.isBasicType(field.getType()) && convertNestedToJsonString) {
                    value = getJsonWriterNoIdent().writeValueAsString(value);
                }
                map.put(name, value);
            }
        }
    } catch (Exception ex) {
        logger.error(null, ex);
    }

    return map;
}