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:py.una.pol.karaku.dao.search.SearchHelper.java

/**
 * Retorna la informacin relacionada a un Field definido por una propiedad
 * (con un formato separado por puntos).
 * <p>/*from   w  ww .java  2 s.  c o m*/
 * Por ejemplo, si invocamos de la siguiente manera:
 * 
 * <pre>
 *    class Pais {
 *       ...
 *       Set{@literal <}Departamento> departamentos;
 * 
 *       ...
 *    }
 * 
 *    class Departamento {
 *       ...
 *       Set{@literal <}Ciudad> ciudades;
 * 
 *       Set etnias;
 * 
 *       Pais pais;
 *       ...
 *    }
 * 
 *    class Ciudad {
 *       ...
 * 
 *       Departamento departamento;
 *       ...
 *    }
 * 
 * 1. Y invocamos de la siguiente manera:
 * 
 *    fi = getFieldInfo(Ciudad.class, "departamento.pais");
 *    fi.getField() ==> Pais.class
 *    fi.isCollection() == > <code>false</code>
 * 
 * 2. El siguiente ejemplo, es cuando se encuentra una {@link Collection}
 * 
 *    fi = getFieldInfo(Ciudad.class, "departamento.etnias");
 *    fi.getField() ==> Etnia.class
 *    fi.isCollection() == > <code>true</code>
 * </pre>
 * 
 * <p>
 * TODO ver para meter en una clase de utilidad
 * </p>
 * 
 * @param root
 *            {@link Class} que sirve de base para buscar la propiedad
 * @param property
 *            cadena separada por <code>.</code> (puntos) que sirve para
 *            recorrer a travs del objeto y obtener la propiedad deseada.
 * @return {@link FieldInfo} con la informacin posible que se ha
 *         conseguido.
 * @throw {@link KarakuRuntimeException} si no encuentra el field o no es
 *        accesible.
 */
public static FieldInfo getFieldInfo(@NotNull Class<?> root, @NotNull String property) {

    try {
        String[] splited = property.split(Pattern.quote("."));
        String cProperty;
        Class<?> cClass = root;
        Field toRet = null;
        boolean collectionFound = false;
        for (String element : splited) {
            cProperty = element;
            toRet = ReflectionUtils.findField(cClass, cProperty);
            if (toRet == null) {
                throw new KarakuRuntimeException(
                        "Field: " + cProperty + " not found. (Full path: " + property + ")");
            }
            cClass = toRet.getType();
            // Si tenemos una lista, buscar el tipo de la lista.
            if (Collection.class.isAssignableFrom(cClass)) {
                cClass = GenericCollectionTypeResolver.getCollectionFieldType(toRet);
            }
            // TODO add expansion if found a @Display in the last field
            // Ejemplo: pais.departamento, puede seguir siendo explotado
            // si departamento tiene un DisplayName
        }
        return new FieldInfo(toRet, collectionFound);
    } catch (SecurityException e) {
        throw new KarakuRuntimeException(
                "Field not accessible: " + property + " in class " + root.getSimpleName(), e);
    }
}

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

/**
  * Get a list of subconfiguration objects for a class instance (<code>X</code>). This 
  * method will do the following:/*from w w w .j av a2 s.c  om*/
  * 
  * <ul>
  *   <li> Identify any fields in the input <code>X</code> which carry the
  *        <code>@Parameter</code> and <code>@Submodel</code> annotations.
  *   <li> If <code>X</code> is an instance of {@link ComponentConfiguration}, and
  *        the ID of the accompanying <code>@Parameter</code> annotation is nonempty,
  *        set the scope string of the field to the parameter ID.
  *   <li> Add a reference to the field to a list <code>L</code>.
  *   <li> Repeat the above steps depth-first recursively for each field in <code>X</code>.
  *   <li> Return <code>L</code>
  * </ul>
  * 
  * @param on <br>
  *        The class instance <code>X</code> to search.
  */
public static List<ComponentConfiguration> getSubconfigurators(final Object on) {
    final Class<?> objClass = Preconditions.checkNotNull(on).getClass();
    final List<ComponentConfiguration> result = new ArrayList<ComponentConfiguration>();
    for (Class<?> typeToSearch = objClass; typeToSearch != null; typeToSearch = typeToSearch.getSuperclass()) {
        for (final Field field : typeToSearch.getDeclaredFields()) {
            if (!ComponentConfiguration.class.isAssignableFrom(field.getType()))
                continue;
            field.setAccessible(true);
            try {
                Annotation drilldownAnnotation = null, modelParameterAnnotation = null;
                for (final Annotation element : field.getAnnotations()) {
                    if (element.annotationType().getName() == Submodel.class.getName()) { // Proxies
                        drilldownAnnotation = element;
                        continue;
                    } else if (element.annotationType().getName() == Parameter.class.getName()) { // Proxies
                        modelParameterAnnotation = element;
                        continue;
                    } else
                        continue;
                }
                if (modelParameterAnnotation != null && drilldownAnnotation != null) {
                    final Object value = field.get(on);
                    if (value == null)
                        throw new IllegalStateException(on.getClass().getSimpleName()
                                + ": the value of a configurator member field" + " in "
                                + (on.getClass().getSimpleName() + on.hashCode()) + " is null.");
                    result.add((ComponentConfiguration) value);
                    final boolean isScoped = (Boolean) modelParameterAnnotation.annotationType()
                            .getMethod("Scoped").invoke(modelParameterAnnotation);
                    if (!isScoped)
                        continue;
                    final String id = (String) modelParameterAnnotation.annotationType().getMethod("ID")
                            .invoke(modelParameterAnnotation);
                    if (id.isEmpty())
                        continue;
                    ((ComponentConfiguration) value).setScope(id);
                }
            } catch (final SecurityException e) {
                throw new IllegalStateException(on.getClass().getSimpleName()
                        + ": a security exception was raised when testing a field with name " + field.getName()
                        + " for model parameter annotations. Details follow: " + e.getMessage() + ".");
            } catch (final IllegalArgumentException e) {
                throw new IllegalStateException(on.getClass().getSimpleName()
                        + "search: an illegal argument exception was raised when testing a field with name "
                        + field.getName() + " for model parameter annotations. Details follow: "
                        + e.getMessage() + ".");
            } catch (final IllegalAccessException e) {
                throw new IllegalStateException(on.getClass().getSimpleName()
                        + "search: a security exception was raised when testing a field with name "
                        + field.getName() + " for model parameter annotations. Details follow: "
                        + e.getMessage() + ".");
            } catch (final InvocationTargetException e) {
                throw new IllegalStateException(on.getClass().getSimpleName()
                        + "search: an invokation target exception was raised when testing a field with"
                        + " name " + field.getName() + " for model parameter annotations. Details follow: "
                        + e.getMessage() + ".");
            } catch (final NoSuchMethodException e) {
                throw new IllegalStateException(on.getClass().getSimpleName()
                        + "search: a missing-method exception was raised when testing a field with name "
                        + field.getName() + " for model parameter annotations. Details follow: "
                        + e.getMessage() + ".");
            }
        }
    }
    return result;
}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Attempt to find a {@link Field field} on the supplied {@link Class} with the
 * supplied {@code name} and/or {@link Class type}. Searches all superclasses
 * up to {@link Object}.//from www  .jav a 2 s  .  c  o  m
 * @param clazz the class to introspect
 * @param name the name of the field (may be {@code null} if type is specified)
 * @param type the type of the field (may be {@code null} if name is specified)
 * @return the corresponding Field object, or {@code null} if not found
 */
public static Field findField(Class<?> clazz, String name, Class<?> type) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.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) {
        Field[] fields = searchType.getDeclaredFields();
        for (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:me.xiaopan.android.gohttp.requestobject.RequestParser.java

/**
 * ?type//from  ww  w.  ja  v  a2  s .  c o  m
 */
private static boolean isArrayByType(Field field, Class<?> type) {
    Class<?> fieldType = field.getType();
    return fieldType.isArray() && type.isAssignableFrom(fieldType.getComponentType());
}

From source file:com.github.dactiv.common.utils.ReflectionUtils.java

/**
 * /*ww w.j av  a  2 s .co m*/
 * ?o??
 * 
 * @param targetClass
 *            Class
 * @param type
 *            ????
 * 
 * @return List
 */
public static List<String> getAccessibleFieldNames(final Class targetClass, Class type) {

    Assert.notNull(targetClass, "targetClass?");
    Assert.notNull(type, "type?");

    List<String> list = new ArrayList<String>();

    for (Field field : targetClass.getDeclaredFields()) {
        if (field.getType().equals(type)) {
            list.add(field.getName());
        }
    }

    return list;
}

From source file:com.datatorrent.lib.util.PojoUtils.java

/**
 * Return the getter expression for the given field.
 * <p>//ww w  .ja v  a  2 s  .c om
 * 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 {}. 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 {}. Proceeding to locate another getter method.",
                pojoClass, methodName, method.getReturnType(), exprClass);
    } catch (NoSuchMethodException | 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 {}. Proceeding with the original expression {}.",
                pojoClass, methodName, method.getReturnType(), exprClass, fieldExpression);
    } catch (NoSuchMethodException | SecurityException ex) {
        logger.debug("{} does not have method {}. Proceeding with the original expression {}.", pojoClass,
                methodName, fieldExpression);
    }

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

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

public static void checkLegalCloudInvocationInfoDef(Object obj) {

    for (Field f : obj.getClass().getDeclaredFields()) {
        if (f.getAnnotation(CloudInvocationInfos.class) != null) {

            Type[] genericTypes = ((ParameterizedType) f.getGenericType()).getActualTypeArguments();
            Class<?> typeParameter = (Class<?>) genericTypes[0];

            if (!f.getType().equals(List.class) || genericTypes.length != 1
                    || !typeParameter.equals(InvocationInfo.class))
                throw new IllegalDefinitionException("Illegal field type " + f.getType().getName()
                        + " annotated with "
                        + "@CloudInvocationInfos. You may only annotate java.util.List<InvocationInfo> fields.");

            if (Modifier.isStatic(f.getModifiers()))
                throw new IllegalDefinitionException("Illegal field " + f.getName()
                        + " annotated with @CloudInvocationInfos. " + "Field has to be non-static.");

        }/* ww w . ja va 2 s .  c o m*/
    }

}

From source file:com.ricemap.spateDB.operations.RangeQuery.java

/**
 * Performs a range query using MapReduce
 * /*from w w w  .  j a  v  a2  s .  c  o  m*/
 * @param fs
 * @param inputFile
 * @param queryRange
 * @param shape
 * @param output
 * @return
 * @throws IOException
 */
public static long rangeQueryMapReduce(FileSystem fs, Path inputFile, Path userOutputPath, Shape queryShape,
        Shape shape, boolean overwrite, boolean background, QueryInput query) throws IOException {
    JobConf job = new JobConf(FileMBR.class);

    FileSystem outFs = inputFile.getFileSystem(job);
    Path outputPath = userOutputPath;
    if (outputPath == null) {
        do {
            outputPath = new Path(
                    inputFile.toUri().getPath() + ".rangequery_" + (int) (Math.random() * 1000000));
        } while (outFs.exists(outputPath));
    } else {
        if (outFs.exists(outputPath)) {
            if (overwrite) {
                outFs.delete(outputPath, true);
            } else {
                throw new RuntimeException("Output path already exists and -overwrite flag is not set");
            }
        }
    }

    job.setJobName("RangeQuery");
    job.setClass(SpatialSite.FilterClass, RangeFilter.class, BlockFilter.class);
    RangeFilter.setQueryRange(job, queryShape); // Set query range for
    // filter

    ClusterStatus clusterStatus = new JobClient(job).getClusterStatus();
    job.setNumMapTasks(clusterStatus.getMaxMapTasks() * 5);
    job.setNumReduceTasks(3);

    // Decide which map function to use depending on how blocks are indexed
    // And also which input format to use
    if (SpatialSite.isRTree(fs, inputFile)) {
        // RTree indexed file
        LOG.info("Searching an RTree indexed file");
        job.setInputFormat(RTreeInputFormat.class);
    } else {
        // A file with no local index
        LOG.info("Searching a non local-indexed file");
        job.setInputFormat(ShapeInputFormat.class);
    }

    GlobalIndex<Partition> gIndex = SpatialSite.getGlobalIndex(fs, inputFile);
    // if (gIndex != null && gIndex.isReplicated()){
    // job.setMapperClass(RangeQueryMap.class);

    Class<?> OutputKey = NullWritable.class;
    try {
        Class<?> c = shape.getClass();
        Field f = c.getDeclaredField(query.field);
        f.setAccessible(true);
        if (f.getType().equals(Integer.TYPE)) {
            OutputKey = IntWritable.class;
        } else if (f.getType().equals(Double.TYPE)) {
            OutputKey = DoubleWritable.class;
        } else if (f.getType().equals(Long.TYPE)) {
            OutputKey = LongWritable.class;
        }
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    job.setMapOutputKeyClass(OutputKey);
    switch (query.type) {
    case Distinct:
        job.setMapperClass(DistinctQueryMap.class);
        job.setReducerClass(DistinctQueryReduce.class);
        job.setMapOutputValueClass(NullWritable.class);
        break;
    case Distribution:
        job.setMapperClass(DistributionQueryMap.class);
        job.setReducerClass(DistributionQueryReduce.class);
        job.setMapOutputValueClass(IntWritable.class);
        break;
    default:
        break;
    }
    // }
    // else
    // job.setMapperClass(RangeQueryMapNoDupAvoidance.class);

    // Set query range for the map function
    job.set(QUERY_SHAPE_CLASS, queryShape.getClass().getName());
    job.set(QUERY_SHAPE, queryShape.toText(new Text()).toString());
    job.set(QUERY_FIELD, query.field);

    // Set shape class for the SpatialInputFormat
    SpatialSite.setShapeClass(job, shape.getClass());

    job.setOutputFormat(TextOutputFormat.class);

    ShapeInputFormat.setInputPaths(job, inputFile);
    TextOutputFormat.setOutputPath(job, outputPath);

    // Submit the job
    if (!background) {
        RunningJob runningJob = JobClient.runJob(job);
        Counters counters = runningJob.getCounters();
        Counter outputRecordCounter = counters.findCounter(Task.Counter.MAP_OUTPUT_RECORDS);
        final long resultCount = outputRecordCounter.getValue();

        // If outputPath not set by user, automatically delete it
        if (userOutputPath == null)
            outFs.delete(outputPath, true);

        return resultCount;
    } else {
        JobClient jc = new JobClient(job);
        lastRunningJob = jc.submitJob(job);
        return -1;
    }
}

From source file:com.zlfun.framework.excel.ExcelUtils.java

private static String get(Object obj, Field field) {

    try {/*  w  w  w .jav a  2s .  c  o  m*/
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }

        if (field.getType() == int.class) {
            return String.valueOf(field.getInt(obj));

        } else if (field.getType() == long.class) {
            return String.valueOf(field.getLong(obj));

        } else if (field.getType() == double.class) {
            return String.valueOf(field.getDouble(obj));
        } else if (field.getType() == byte.class) {
            return String.valueOf(field.getByte(obj));
        } else if (field.getType() == boolean.class) {
            return String.valueOf(field.getBoolean(obj));
        } else if (field.getType() == String.class) {
            if (field.get(obj) == null) {
                return "";
            }
            return String.valueOf(field.get(obj));
        } else if (field.getType() == Date.class) {
            if (field.get(obj) == null) {
                return "";
            }
            return MiscDateUtils.getDateTime((Date) field.get(obj));
        }

    } catch (Exception e) {

    }
    return "";
}

From source file:com.datatorrent.lib.util.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  .  co 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 (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();
}