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.sugaronrest.restapicalls.ModuleInfo.java

/**
 * Gets json names from module fields annotations.
 *
 * @param type The Java module type./*w w  w. j a v  a2  s  .com*/
 * @return List of json property names.
 */
private static List<ModuleProperty> getFieldAnnotations(Class type) {
    List<ModuleProperty> modelProperties = new ArrayList<ModuleProperty>();
    Iterable<Field> fields = getFieldsUpTo(type, Object.class);
    for (Field field : fields) {
        Annotation[] annotations = field.getAnnotations();

        for (Annotation annotation : annotations) {
            if (annotation instanceof JsonProperty) {
                JsonProperty property = (JsonProperty) annotation;
                ModuleProperty moduleProperty = new ModuleProperty();
                moduleProperty.name = field.getName();
                moduleProperty.jsonName = property.value();
                moduleProperty.type = field.getType();
                moduleProperty.isNumeric = isTypeNumeric(field.getType());
                modelProperties.add(moduleProperty);
            }
        }
    }

    return modelProperties;
}

From source file:br.gov.frameworkdemoiselle.ldap.internal.ClazzUtils.java

public static Object getValueAsFieldType(Field field, Object values, boolean cascade) {
    if (values instanceof String[]) {
        String[] valueArray = (String[]) values;

        if (valueArray == null || valueArray.length == 0)
            return null;

        if (field.getType().isAssignableFrom(String.class))
            return valueArray[0];

        if (field.getType().isArray())
            if (field.getType().getComponentType().isAssignableFrom(String.class))
                return valueArray;

        if (field.getType().isPrimitive()) {

            if (field.getType().isAssignableFrom(int.class))
                return Integer.valueOf(valueArray[0]);

            if (field.getType().isAssignableFrom(long.class))
                return Long.valueOf(valueArray[0]);

            if (field.getType().isAssignableFrom(double.class))
                return Double.valueOf(valueArray[0]);

            if (field.getType().isAssignableFrom(float.class))
                return Float.valueOf(valueArray[0]);

            if (field.getType().isAssignableFrom(short.class))
                return Short.valueOf(valueArray[0]);

            if (field.getType().isAssignableFrom(byte.class))
                return Byte.valueOf(valueArray[0]);

        }/* w  w  w  . j  ava  2s  . co  m*/

        if (isAnnotationPresent(field.getType(), LDAPEntry.class, false))
            return getMappedEntryObject(field.getType(), valueArray, cascade);

        if (field.getType().isAssignableFrom(ArrayList.class))
            if (String.class.isAssignableFrom(Reflections.getGenericTypeArgument(field.getType(), 0)))
                return new ArrayList<String>(Arrays.asList(valueArray));

        if (field.getType().isAssignableFrom(Integer.class))
            return Integer.valueOf(valueArray[0]);

        if (field.getType().isAssignableFrom(Long.class))
            return Long.valueOf(valueArray[0]);

        if (field.getType().isAssignableFrom(Double.class))
            return Double.valueOf(valueArray[0]);

        if (field.getType().isAssignableFrom(Float.class))
            return Float.valueOf(valueArray[0]);

        if (field.getType().isAssignableFrom(Short.class))
            return Short.valueOf(valueArray[0]);

        if (field.getType().isAssignableFrom(Byte.class))
            return Byte.valueOf(valueArray[0]);

        logger.error("Handling not implemented for field " + field.getName() + " with type "
                + field.getType().getSimpleName());

    } else if (values instanceof byte[][]) {

        if (field.getType().isAssignableFrom(byte[][].class))
            return values;

        if (field.getType().isAssignableFrom(byte[].class))
            return ((byte[][]) values)[0];

        logger.error("Binary data from LDAP can't be set in " + field.getName() + " with type "
                + field.getType().getSimpleName());

    }

    logger.error("Object value should be String[] or byte[][]. The value type " + values.getClass()
            + " can't be set in " + field.getName() + " with type " + field.getType().getSimpleName());
    return null;
}

From source file:com.smartitengineering.util.bean.BeanFactoryRegistrar.java

private static boolean aggregate(Class<? extends Object> aggregatorClass, Object aggregator)
        throws SecurityException {
    if (aggregatorClass.equals(Object.class)) {
        return true;
    }/*from   w w w. j av  a  2  s. c  o m*/
    Class<? extends Object> superClass = aggregatorClass.getSuperclass();
    if (superClass != null) {
        aggregate(superClass, aggregator);
    }
    Aggregator aggregatorAnnotation = aggregatorClass.getAnnotation(Aggregator.class);
    if (aggregatorAnnotation == null || StringUtils.isBlank(aggregatorAnnotation.contextName())) {
        return true;
    }
    BeanFactory beanFactory = getBeanFactorForContext(aggregatorAnnotation.contextName());
    if (beanFactory == null) {
        return true;
    }
    Field[] declaredFields = aggregatorClass.getDeclaredFields();
    for (Field declaredField : declaredFields) {
        InjectableField injectableField = declaredField.getAnnotation(InjectableField.class);
        if (injectableField == null) {
            continue;
        }
        String beanName = StringUtils.isBlank(injectableField.beanName()) && beanFactory.isNameMandatory()
                ? declaredField.getName()
                : injectableField.beanName();
        if (StringUtils.isBlank(beanName) && beanFactory.isNameMandatory()) {
            return true;
        }
        try {
            declaredField.setAccessible(true);
            final Class<?> fieldType = declaredField.getType();
            if (beanFactory.containsBean(beanName, fieldType)) {
                declaredField.set(aggregator, beanFactory.getBean(beanName, fieldType));
            }
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        }

    }
    return false;
}

From source file:com.zb.app.common.core.lang.BeanUtils.java

/**
 * ?Beanmap,map// w  ww . j  av  a2  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>();
    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.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.liferay.cli.support.util.ReflectionUtils.java

/**
 * Attempt to find a {@link Field field} on the supplied {@link Class} with
 * the supplied <code>name</code> and/or {@link Class type}. Searches all
 * superclasses up to {@link Object}.//from   w  w w  . j av a  2s.c  o  m
 * 
 * @param clazz the class to introspect
 * @param name the name of the field (may be <code>null</code> if type is
 *            specified)
 * @param type the type of the field (may be <code>null</code> if name is
 *            specified)
 * @return the corresponding Field object, or <code>null</code> if not found
 */
public static Field findField(final Class<?> clazz, final String name, final Class<?> type) {
    Validate.notNull(clazz, "Class must not be null");
    Validate.isTrue(name != null || type != null, "Either name or type of the field must be specified");
    Class<?> searchType = clazz;
    while (!Object.class.equals(searchType) && searchType != null) {
        final Field[] fields = searchType.getDeclaredFields();
        for (final Field field : fields) {
            if ((name == null || name.equals(field.getName()))
                    && (type == null || type.equals(field.getType()))) {
                return field;
            }
        }
        searchType = searchType.getSuperclass();
    }
    return null;
}

From source file:com.iisigroup.cap.utils.CapBeanUtil.java

public static <T> T setField(T entry, String fieldId, Object value) {
    Field field = ReflectionUtils.findField(entry.getClass(), fieldId);
    if (field != null) {
        String setter = new StringBuffer("set").append(String.valueOf(field.getName().charAt(0)).toUpperCase())
                .append(field.getName().substring(1)).toString();
        Method method = ReflectionUtils.findMethod(entry.getClass(), setter, new Class[] { field.getType() });
        if (method != null) {
            try {
                if (field.getType() != String.class && "".equals(value)) {
                    value = null;/*w  w w . ja va 2  s.c  o m*/
                } else if (field.getType() == BigDecimal.class) {
                    value = CapMath.getBigDecimal(String.valueOf(value));
                } else if (value instanceof String) {
                    if (field.getType() == java.util.Date.class || field.getType() == java.sql.Date.class) {
                        value = CapDate.parseDate((String) value);
                    } else if (field.getType() == Timestamp.class) {
                        value = CapDate.convertStringToTimestamp1((String) value);
                    }
                }
                if (value == null) {
                    method.invoke(entry, new Object[] { null });
                } else {
                    method.invoke(entry, ConvertUtils.convert(value, field.getType()));
                }
            } catch (Exception e) {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace(e.getMessage());
                } else {
                    LOGGER.warn(e.getMessage(), e);
                }
            }
        }
    }
    return entry;
}

From source file:com.tugo.dt.PojoUtils.java

/**
 * Return the getter expression for the given field.
 * <p>/*from   w  w  w  .j a  v a 2  s .  c o  m*/
 * If the field is a public member, the field name is used else the getter function. If no matching field or getter
 * method is found, the expression is returned unmodified.
 *
 * @param pojoClass class to check for the field
 * @param fieldExpression field name expression
 * @param exprClass expected field type
 * @return java code fragment
 */
private static String getSingleFieldGetterExpression(final Class<?> pojoClass, final String fieldExpression,
        final Class<?> exprClass) {
    JavaStatement code = new JavaReturnStatement(
            pojoClass.getName().length() + fieldExpression.length() + exprClass.getName().length() + 32,
            exprClass);
    code.appendCastToTypeExpr(pojoClass, OBJECT).append(".");
    try {
        final Field field = pojoClass.getField(fieldExpression);
        if (ClassUtils.isAssignable(field.getType(), exprClass)) {
            return code.append(field.getName()).getStatement();
        }
        logger.debug("Field {} can not be assigned to an {}. Proceeding to locate a getter method.", field,
                exprClass);
    } catch (NoSuchFieldException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a getter method.", pojoClass,
                fieldExpression);
    } catch (SecurityException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a getter method.", pojoClass,
                fieldExpression);
    }

    String methodName = GET + upperCaseWord(fieldExpression);
    try {
        Method method = pojoClass.getMethod(methodName);
        if (ClassUtils.isAssignable(method.getReturnType(), exprClass)) {
            return code.append(methodName).append("()").getStatement();
        }
        logger.debug(
                "method {} of the {} returns {} that can not be assigned to an {}. Proceeding to locate another getter method.",
                pojoClass, methodName, method.getReturnType(), exprClass);
    } catch (NoSuchMethodException ex) {
        logger.debug("{} does not have method {}. Proceeding to locate another getter method.", pojoClass,
                methodName);
    } catch (SecurityException ex) {
        logger.debug("{} does not have method {}. Proceeding to locate another getter method.", pojoClass,
                methodName);
    }

    methodName = IS + upperCaseWord(fieldExpression);
    try {
        Method method = pojoClass.getMethod(methodName);
        if (ClassUtils.isAssignable(method.getReturnType(), exprClass)) {
            return code.append(methodName).append("()").getStatement();
        }
        logger.debug(
                "method {} of the {} returns {} that can not be assigned to an {}. Proceeding with the original expression {}.",
                pojoClass, methodName, method.getReturnType(), exprClass, fieldExpression);
    } catch (NoSuchMethodException ex) {
        logger.debug("{} does not have method {}. Proceeding with the original expression {}.", pojoClass,
                methodName, fieldExpression);
    } catch (SecurityException ex) {
        logger.debug("{} does not have method {}. Proceeding with the original expression {}.", pojoClass,
                methodName, fieldExpression);
    }

    return code.append(fieldExpression).getStatement();
}

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

public static List<GetterSetterPair> parameters(final Object of, final Class<?> paramType) {
    final List<GetterSetterPair> result = new ArrayList<GetterSetterPair>();
    final Class<?> parentType = of.getClass();
    for (Class<?> typeToSearch = parentType; typeToSearch != null; typeToSearch = typeToSearch
            .getSuperclass()) {//from  www.ja v  a  2s  . c o m
        final Map<String, Method> methodNames = new HashMap<String, Method>();
        final Method[] allCalleeMethods = typeToSearch.getDeclaredMethods();
        for (final Method method : allCalleeMethods) {
            final String name = method.getName();
            if (name.startsWith("get") && ClassUtils.isAssignable(paramType, method.getReturnType(), true))
                methodNames.put(method.getName(), method);
            else if (name.startsWith("set") && method.getParameterTypes().length == 1
                    && ClassUtils.isAssignable(paramType, method.getParameterTypes()[0], true))
                methodNames.put(method.getName(), method);
            else
                continue;
            final String complement;
            if (name.startsWith("get")) {
                complement = "set" + name.substring(3);
                if (methodNames.containsKey(complement))
                    result.add(new GetterSetterPair(method, methodNames.get(complement), of));
            } else if (name.startsWith("set")) {
                complement = "get" + name.substring(3);
                if (methodNames.containsKey(complement))
                    result.add(new GetterSetterPair(methodNames.get(complement), method, of));
            }
        }
    }
    // 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(of);
            } catch (final IllegalArgumentException e) {
                continue; // Not found
            } catch (final IllegalAccessException e) {
                continue; // Not found
            }
            if (instance != null) {
                final List<GetterSetterPair> subResult = parameters(instance, paramType); // Descend into fields
                if (subResult != null && !subResult.isEmpty())
                    result.addAll(subResult);
                else
                    continue;
            }
        }
    }
    return result;
}

From source file:eagle.log.entity.meta.EntityDefinitionManager.java

@SuppressWarnings("unchecked")
public static EntityDefinition createEntityDefinition(Class<? extends TaggedLogAPIEntity> cls) {

    final EntityDefinition ed = new EntityDefinition();

    ed.setEntityClass(cls);/* w w  w  .  j  a  va 2  s  .c om*/
    // parse cls' annotations
    Table table = cls.getAnnotation(Table.class);
    if (table == null || table.value().isEmpty()) {
        throw new IllegalArgumentException(
                "Entity class must have a non-empty table name annotated with @Table");
    }
    String tableName = table.value();
    if (EagleConfigFactory.load().isTableNamePrefixedWithEnvironment()) {
        tableName = EagleConfigFactory.load().getEnv() + "_" + tableName;
    }
    ed.setTable(tableName);

    ColumnFamily family = cls.getAnnotation(ColumnFamily.class);
    if (family == null || family.value().isEmpty()) {
        throw new IllegalArgumentException(
                "Entity class must have a non-empty column family name annotated with @ColumnFamily");
    }
    ed.setColumnFamily(family.value());

    Prefix prefix = cls.getAnnotation(Prefix.class);
    if (prefix == null || prefix.value().isEmpty()) {
        throw new IllegalArgumentException(
                "Entity class must have a non-empty prefix name annotated with @Prefix");
    }
    ed.setPrefix(prefix.value());

    TimeSeries ts = cls.getAnnotation(TimeSeries.class);
    if (ts == null) {
        throw new IllegalArgumentException(
                "Entity class must have a non-empty timeseries name annotated with @TimeSeries");
    }
    ed.setTimeSeries(ts.value());

    Service service = cls.getAnnotation(Service.class);
    if (service == null || service.value().isEmpty()) {
        ed.setService(cls.getSimpleName());
    } else {
        ed.setService(service.value());
    }

    Metric m = cls.getAnnotation(Metric.class);
    Map<String, Class<?>> dynamicFieldTypes = new HashMap<String, Class<?>>();
    if (m != null) {
        // metric has to be timeseries
        if (!ts.value()) {
            throw new IllegalArgumentException("Metric entity must be time series as well");
        }
        MetricDefinition md = new MetricDefinition();
        md.setInterval(m.interval());
        ed.setMetricDefinition(md);
    }

    java.lang.reflect.Field[] fields = cls.getDeclaredFields();
    for (java.lang.reflect.Field f : fields) {
        Column column = f.getAnnotation(Column.class);
        if (column == null || column.value().isEmpty()) {
            continue;
        }
        Class<?> fldCls = f.getType();
        // intrusive check field type for metric entity
        checkFieldTypeForMetric(ed.getMetricDefinition(), f.getName(), fldCls, dynamicFieldTypes);
        Qualifier q = new Qualifier();
        q.setDisplayName(f.getName());
        q.setQualifierName(column.value());
        EntitySerDeser<?> serDeser = _serDeserMap.get(fldCls);
        if (serDeser == null) {
            throw new IllegalArgumentException(fldCls.getName() + " in field " + f.getName() + " of entity "
                    + cls.getSimpleName() + " has no serializer associated ");
        } else {
            q.setSerDeser((EntitySerDeser<Object>) serDeser);
        }
        ed.getQualifierNameMap().put(q.getQualifierName(), q);
        ed.getDisplayNameMap().put(q.getDisplayName(), q);
        // TODO: should refine rules, consider fields like "hCol", getter method should be gethCol() according to org.apache.commons.beanutils.PropertyUtils
        final String propertyName = f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1);
        String getterName = "get" + propertyName;
        try {
            Method method = cls.getMethod(getterName);
            ed.getQualifierGetterMap().put(f.getName(), method);
        } catch (Exception e) {
            // Check if the type is boolean
            getterName = "is" + propertyName;
            try {
                Method method = cls.getMethod(getterName);
                ed.getQualifierGetterMap().put(f.getName(), method);
            } catch (Exception e1) {
                throw new IllegalArgumentException(
                        "Field " + f.getName() + " hasn't defined valid getter method: " + getterName, e);
            }
        }
        if (LOG.isDebugEnabled())
            LOG.debug("Field registered " + q);
    }

    // TODO: Lazy create because not used at all
    // dynamically create bean class
    if (ed.getMetricDefinition() != null) {
        Class<?> metricCls = createDynamicClassForMetric(cls.getName() + "_SingleTimestamp", dynamicFieldTypes);
        ed.getMetricDefinition().setSingleTimestampEntityClass(metricCls);
    }

    final Partition partition = cls.getAnnotation(Partition.class);
    if (partition != null) {
        final String[] partitions = partition.value();
        ed.setPartitions(partitions);
        // Check if partition fields are all tag fields. Partition field can't be column field, must be tag field.
        for (String part : partitions) {
            if (!ed.isTag(part)) {
                throw new IllegalArgumentException("Partition field can't be column field, must be tag field. "
                        + "Partition name: " + part);
            }
        }
    }

    final Indexes indexes = cls.getAnnotation(Indexes.class);
    if (indexes != null) {
        final Index[] inds = indexes.value();
        final IndexDefinition[] indexDefinitions = new IndexDefinition[inds.length];
        for (int i = 0; i < inds.length; ++i) {
            final Index ind = inds[i];
            indexDefinitions[i] = new IndexDefinition(ed, ind);
        }
        ed.setIndexes(indexDefinitions);
    }

    final ServicePath path = cls.getAnnotation(ServicePath.class);
    if (path != null) {
        if (path.path() != null && (!path.path().isEmpty())) {
            ed.setServiceCreationPath(path.path());
        }
    }

    return ed;
}

From source file:com.astamuse.asta4d.data.InjectUtil.java

private final static InstanceWireTarget createInstanceTarget(Object instance) throws DataOperationException {

    InstanceWireTarget target = new InstanceWireTarget();
    Class<?> cls = instance.getClass();

    List<AnnotatedPropertyInfo> propertyList = AnnotatedPropertyUtil.retrieveProperties(cls);

    try {//ww  w.j av a 2 s .  c o  m
        for (AnnotatedPropertyInfo prop : propertyList) {
            ContextData cd = prop.getAnnotation(ContextData.class);

            if (prop.getField() != null) {
                Field field = prop.getField();
                FieldInfo fi = new FieldInfo();
                fi.propertyInfo = prop;
                fi.name = prop.getName();
                fi.field = field;
                fi.type = field.getType();
                fi.isContextDataHolder = ContextDataHolder.class.isAssignableFrom(fi.type);

                fi.scope = cd.scope();
                fi.typeUnMatch = cd.typeUnMatch();
                fi.fixForPrimitiveType();

                ContextDataSet cdSet = ConvertableAnnotationRetriever.retrieveAnnotation(ContextDataSet.class,
                        fi.type.getAnnotations());
                if (cdSet == null) {
                    fi.contextDataSetFactory = null;
                } else {
                    fi.contextDataSetFactory = cdSet.factory().newInstance();
                    fi.isContextDataSetSingletonInContext = cdSet.singletonInContext();
                }

                target.setFieldList.add(fi);

            } else {// for method
                MethodInfo mi = new MethodInfo();
                mi.propertyInfo = prop;
                mi.name = prop.getName();
                mi.method = prop.getSetter();
                if (mi.method == null) {
                    throw new DataOperationException(
                            "Could not find setter method for annotated property:" + prop.getName());
                }
                mi.type = mi.method.getParameterTypes()[0];
                mi.isContextDataHolder = ContextDataHolder.class.isAssignableFrom(mi.type);

                mi.scope = cd.scope();
                mi.typeUnMatch = cd.typeUnMatch();
                mi.fixForPrimitiveType();

                ContextDataSet cdSet = ConvertableAnnotationRetriever.retrieveAnnotation(ContextDataSet.class,
                        mi.type.getAnnotations());
                if (cdSet == null) {
                    mi.contextDataSetFactory = null;
                } else {
                    mi.contextDataSetFactory = cdSet.factory().newInstance();
                    mi.isContextDataSetSingletonInContext = cdSet.singletonInContext();
                }
                target.setMethodList.add(mi);

            }

        }
    } catch (InstantiationException | IllegalAccessException e) {
        throw new DataOperationException(
                "Exception occured on generating injection information of " + instance.getClass(), e);
    }

    return target;
}