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.antsdb.saltedfish.sql.ExternalTable.java

public static <T> ExternalTable wrap(Orca orca, String namespace, Class<T> klass, Iterable<T> iterable) {
    ClassBasedTable<T> table = new ClassBasedTable<>();
    table.source = iterable;/*w w  w  .j a  v a 2 s .c  o m*/
    table.meta.setNamespace(namespace).setTableName(iterable.getClass().getSimpleName());
    List<ColumnMeta> columns = new ArrayList<>();
    for (Field i : klass.getFields()) {
        ColumnMeta column = new ColumnMeta(orca.getTypeFactory(), new SlowRow(0));
        column.setColumnName(i.getName()).setId(table.meta.getColumns().size());
        if (i.getType() == String.class) {
            column.setType(DataType.varchar());
        } else if (i.getType() == int.class) {
            column.setType(DataType.integer());
        } else if (i.getType() == long.class) {
            column.setType(DataType.longtype());
        } else {
            throw new NotImplementedException();
        }
        columns.add(column);
        table.fields.add(i);
    }
    table.meta.setColumns(columns);
    return table;
}

From source file:gr.abiss.calipso.tiers.specifications.GenericSpecifications.java

/**
 * Get an appropriate predicate factory for the given field class
 * @param field/*from  ww w  .  j  a  v a2s. c o  m*/
 * @return
 */
private static IPredicateFactory<?> getPredicateFactoryForClass(Field field) {
    Class clazz = field.getType();
    if (clazz.isEnum()) {
        return new EnumStringPredicateFactory(clazz);
    } else if (Persistable.class.isAssignableFrom(clazz)) {
        if (field.isAnnotationPresent(CurrentPrincipal.class)) {
            return currentPrincipalPredicateFactory;
        } else {
            return anyToOnePredicateFactory;
        }
    } else {
        return factoryForClassMap.get(clazz);
    }
}

From source file:com.antsdb.saltedfish.util.CursorUtil.java

public static CursorMeta toMeta(Class<?> klass) {
    CursorMeta meta = new CursorMeta();
    for (Field i : klass.getFields()) {
        FieldMeta column = new FieldMeta();
        column.setName(i.getName());/*  w  ww.  j  a v a 2s . c o m*/
        if (i.getType() == String.class) {
            column.setType(DataType.varchar());
        } else if (i.getType() == int.class) {
            column.setType(DataType.integer());
        } else if (i.getType() == Integer.class) {
            column.setType(DataType.integer());
        } else if (i.getType() == long.class) {
            column.setType(DataType.longtype());
        } else if (i.getType() == Long.class) {
            column.setType(DataType.longtype());
        } else if (i.getType() == Timestamp.class) {
            column.setType(DataType.timestamp());
        } else if (i.getType() == byte[].class) {
            column.setType(DataType.blob());
        } else {
            throw new NotImplementedException();
        }
        meta.addColumn(column);
    }
    return meta;
}

From source file:com.hortonworks.registries.common.util.ReflectionHelper.java

/**
 * Given a class, this method returns a map of names of all the instance (non static) fields to type.
 * if the class has any super class it also includes those fields.
 * @param clazz , not null/*from   w w  w.  j av a 2s . co m*/
 * @return
 */
public static Map<String, Class> getFieldNamesToTypes(Class clazz) {
    Field[] declaredFields = clazz.getDeclaredFields();
    Map<String, Class> instanceVariableNamesToTypes = new HashMap<>();
    for (Field field : declaredFields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            LOG.trace("clazz {} has field {} with type {}", clazz.getName(), field.getName(),
                    field.getType().getName());
            instanceVariableNamesToTypes.put(field.getName(), field.getType());
        } else {
            LOG.trace("clazz {} has field {} with type {}, which is static so ignoring", clazz.getName(),
                    field.getName(), field.getType().getName());
        }
    }

    if (!clazz.getSuperclass().equals(Object.class)) {
        instanceVariableNamesToTypes.putAll(getFieldNamesToTypes(clazz.getSuperclass()));
    }
    return instanceVariableNamesToTypes;
}

From source file:utils.ReflectionService.java

public static JsonNode createJsonNode(Class clazz, int maxDeep) {

    if (maxDeep <= 0 || JsonNode.class.isAssignableFrom(clazz)) {
        return null;
    }//from   w  w  w  . ja  va  2 s  .c o m

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode objectNode = objectMapper.createObjectNode();

    for (Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);
        String key = field.getName();
        try {
            // is array or collection
            if (field.getType().isArray() || Collection.class.isAssignableFrom(field.getType())) {
                ParameterizedType collectionType = (ParameterizedType) field.getGenericType();
                Class<?> type = (Class<?>) collectionType.getActualTypeArguments()[0];
                ArrayNode arrayNode = objectMapper.createArrayNode();
                arrayNode.add(createJsonNode(type, maxDeep - 1));
                objectNode.put(key, arrayNode);
            } else {
                Class<?> type = field.getType();
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                } else if (type.isEnum()) {
                    objectNode.put(key, Enum.class.getName());
                } else if (!type.getName().startsWith("java") && !key.startsWith("_")) {
                    objectNode.put(key, createJsonNode(type, maxDeep - 1));
                } else {
                    objectNode.put(key, type.getName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return objectNode;
}

From source file:com.adobe.acs.commons.mcp.util.AnnotatedFieldDeserializer.java

private static void parseInputValue(Object target, String value, Field field)
        throws ReflectiveOperationException, ParseException {
    FieldUtils.writeField(field, target, convertValue(value, field.getType()), true);
}

From source file:Main.java

/**
 * Sets the given field's value of the specified object instance.
 * /*from  www .  j a  va  2 s . c om*/
 * @throws IllegalArgumentException if the value cannot be set.
 */
public static void setValue(final Field field, final Object instance, final Object value) {
    try {
        field.setAccessible(true);
        field.set(instance, convert(value, field.getType()));
    } catch (final IllegalAccessException e) {
        throw new IllegalArgumentException("No access to field: " + field.getName(), e);
    }
}

From source file:Main.java

private static ArrayList<ArrayList> sortObjectArrayListSimpleMaster(ArrayList listIn, String paramName) {
    ArrayList<ArrayList> answer = new ArrayList<ArrayList>();
    ArrayList newList = new ArrayList();
    ArrayList<Integer> indices = new ArrayList<Integer>();
    try {/*w w  w.  ja  v a  2 s .com*/
        if (listIn.size() > 0) {
            Class<?> c = listIn.get(0).getClass();
            Field f = c.getDeclaredField(paramName);
            f.setAccessible(true);
            Class<?> t = f.getType();
            Double dd = new Double(14);
            Float ff = new Float(14);
            Integer ii = new Integer(14);
            Map sortedPos = new LinkedHashMap();
            Map sortedNeg = new LinkedHashMap();
            Map unsorted = new LinkedHashMap();
            int indexCount = 0;
            long count = 0;
            if (t.isPrimitive()) {
                for (Object thisObj : listIn) {
                    Object o = f.get(thisObj);
                    double d = 0;
                    if (t.getName().equals("char")) {
                        d = (int) ((Character) o);
                    } else if (t.isInstance(dd))
                        d = (Double) o;
                    else if (t.isInstance(ff))
                        d = (Float) o;
                    else if (t.isInstance(ii))
                        d = (Integer) o;
                    else
                        d = new Double(o.toString());

                    boolean isNegative = false;

                    if (d < 0) {
                        isNegative = true;
                        d = Math.abs(d);
                    }

                    String format = "%1$30f";
                    String newKey = String.format(format, d);
                    String format2 = "%1$20d";
                    String countString = String.format(format2, count);
                    newKey += "-" + countString;
                    if (isNegative) {
                        sortedNeg.put(newKey, thisObj);
                    } else {
                        sortedPos.put(newKey, thisObj);
                    }
                    unsorted.put(thisObj, indexCount);
                    count++;
                    indexCount++;
                }
                TreeMap<String, Object> resultPos = new TreeMap();
                resultPos.putAll(sortedPos);
                sortedPos = resultPos;
                TreeMap<String, Object> resultNeg = new TreeMap();
                resultNeg.putAll(sortedNeg);
                sortedNeg = resultNeg;
            } else if (t.isInstance(paramName)) {
                // System.out.println("is a string with value " + o);
                for (Object thisObj : listIn) {
                    String key = (String) (f.get(thisObj));
                    sortedPos.put(key + "-" + count, thisObj);
                    unsorted.put(thisObj, indexCount);
                    count++;
                    indexCount++;
                }
                TreeMap<String, Object> result = new TreeMap(String.CASE_INSENSITIVE_ORDER);
                result.putAll(sortedPos);
                sortedPos = result;
            }

            Iterator itNeg = sortedNeg.entrySet().iterator();
            while (itNeg.hasNext()) {
                Map.Entry pairs = (Map.Entry) itNeg.next();
                newList.add(pairs.getValue());
                itNeg.remove();
            }

            Collections.reverse(newList);

            Iterator itPos = sortedPos.entrySet().iterator();
            while (itPos.hasNext()) {
                Map.Entry pairs = (Map.Entry) itPos.next();
                Object obj = pairs.getValue();
                newList.add(obj);
                indices.add((Integer) unsorted.get(obj));
                itPos.remove();
            }
        }
    } catch (Exception e) {
        System.out
                .println("problem sorting list.  listIn.size(): " + listIn.size() + " and param: " + paramName);
        answer.add(newList);
        answer.add(indices);
        return answer;
    }
    answer.add(newList);
    answer.add(indices);
    return answer;
}

From source file:org.LexGrid.LexBIG.caCore.utils.LexEVSCaCoreUtils.java

public static <T> T recurseReflect(final T obj, final DoInReflectionCallback callback) {
    if (obj == null) {
        return null;
    }// w  ww. j a  va 2s .  co  m
    ReflectionUtils.doWithFields(obj.getClass(), new FieldCallback() {

        public void doWith(Field arg0) throws IllegalArgumentException, IllegalAccessException {

            if (!ClassUtils.isPrimitiveOrWrapper(arg0.getType()) && !ClassUtils.isPrimitiveArray(arg0.getType())
                    && !ClassUtils.isPrimitiveWrapperArray(arg0.getType()) && !arg0.getType().isEnum()
                    && (isLexBigClass(arg0.getType()) || Collection.class.isAssignableFrom(arg0.getType())
                            || Map.class.isAssignableFrom(arg0.getType()))) {

                arg0.setAccessible(true);
                Object recurse = arg0.get(obj);

                if (recurse != null) {

                    if (CycleDetectingCallback.class.isAssignableFrom(recurse.getClass())) {
                        System.out.println("ere");
                    }

                    if (Collection.class.isAssignableFrom(recurse.getClass())) {
                        Collection collection = (Collection) recurse;
                        for (Object o : collection) {
                            if (callback.actionRequired(o)) {
                                collection.remove(o);
                                collection.add(recurseReflect(o, callback));
                            } else {
                                recurseReflect(o, callback);
                            }
                        }
                    } else if (Map.class.isAssignableFrom(recurse.getClass())) {
                        Map map = (Map) recurse;
                        for (Object key : map.keySet()) {
                            Object value = map.get(key);
                            if (callback.actionRequired(key) || callback.actionRequired(value)) {
                                map.remove(key);
                                map.put(recurseReflect(key, callback), recurseReflect(value, callback));
                            } else {
                                recurseReflect(key, callback);
                                recurseReflect(value, callback);
                            }
                        }
                    } else {
                        if (callback.actionRequired(recurse)) {
                            Object newObject = recurseReflect(recurse, callback);
                            arg0.set(obj, newObject);
                        } else {
                            recurseReflect(recurse, callback);
                        }
                    }
                }
            }
        }
    });

    return callback.doInReflection(obj);
}

From source file:com.robertsmieja.test.utils.junit.GettersAndSettersUtils.java

static Method getSetterForField(Field field) {
    return MethodUtils.getAccessibleMethod(field.getDeclaringClass(),
            accessorMethodNameForField(GettersAndSettersTests.SET_METHOD_PREFIX, field), field.getType());
}