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:cop.raml.mocks.MockUtils.java

private static TypeElementMock createClassElement(@NotNull Class<?> cls) throws ClassNotFoundException {
    TypeElementMock element = new TypeElementMock(cls.getName(), ElementKind.CLASS);
    element.setType(new TypeMirrorMock(element, TypeMirrorMock.getTypeKind(cls)));

    if (cls.getName().startsWith("cop.") || cls.getName().startsWith("spring.")) {
        VariableElementMock var;

        for (Field field : cls.getDeclaredFields())
            if ((var = createVariable(field.getName(), field.getType(),
                    Modifier.isStatic(field.getModifiers()))) != null)
                element.addEnclosedElement(setAnnotations(var, field));

        ExecutableElementMock exe;/*from  ww w.  j a v a 2s  .  c  o m*/

        for (Method method : cls.getDeclaredMethods())
            if ((exe = createExecutable(method)) != null)
                element.addEnclosedElement(setAnnotations(exe, method));
    }

    return setAnnotations(element, cls);
}

From source file:ClassTree.java

/**
 * Returns a description of the fields of a class.
 * @param the class to be described/*from www .  ja v a2  s. c om*/
 * @return a string containing all field types and names
 */
public static String getFieldDescription(Class<?> c) {
    // use reflection to find types and names of fields
    StringBuilder r = new StringBuilder();
    Field[] fields = c.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        Field f = fields[i];
        if ((f.getModifiers() & Modifier.STATIC) != 0)
            r.append("static ");
        r.append(f.getType().getName());
        r.append(" ");
        r.append(f.getName());
        r.append("\n");
    }
    return r.toString();
}

From source file:utils.ReflectionService.java

public static Map createClassModel(Class clazz, int maxDeep) {
    Map map = new HashMap();
    for (Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);//from   w  w w . j av  a  2 s. c o m
        String key = field.getName();
        try {
            Class<?> type;
            if (Collection.class.isAssignableFrom(field.getType())) {
                ParameterizedType collectionType = (ParameterizedType) field.getGenericType();
                type = (Class<?>) collectionType.getActualTypeArguments()[0];
            } else {
                type = field.getType();
            }

            //            System.out.println(key + " ReflectionResource.createClassModel ==== putting type: " + field.getType().getName() + ", static: "
            //            + Modifier.isStatic(field.getModifiers()) + ", enum: " + type.isEnum() + ", java.*: " + type.getName().startsWith("java"));

            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            } else if (type.isEnum()) {
                map.put(key, Enum.class.getName());
            } else if (!type.getName().startsWith("java") && !key.startsWith("_") && maxDeep > 0) {
                map.put(key, createClassModel(type, maxDeep - 1));
            } else {
                map.put(key, type.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return map;
}

From source file:org.mstc.zmq.json.Encoder.java

public static String encode(Object o) throws IOException {
    StringWriter writer = new StringWriter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
    JsonFactory factory = mapper.getFactory();
    try (JsonGenerator g = factory.createGenerator(writer)) {
        g.writeStartObject();/*from w  w w .  j a  va2  s .  c  o m*/
        for (Field f : o.getClass().getDeclaredFields()) {
            try {
                f.setAccessible(true);
                Object value = f.get(o);
                if (value != null) {
                    if (f.getType().isAssignableFrom(List.class)) {
                        String items = mapper.writeValueAsString(value);
                        g.writeStringField(f.getName(), items);
                    } else if (f.getType().isArray()) {
                        if (f.getType().getComponentType().isAssignableFrom(byte.class)) {
                            g.writeBinaryField(f.getName(), (byte[]) value);
                        } else {
                            int length = Array.getLength(value);
                            g.writeFieldName(f.getName());
                            g.writeStartArray();
                            for (int i = 0; i < length; i++) {
                                Object av = Array.get(value, i);
                                if (av instanceof Double) {
                                    g.writeNumber(new BigDecimal((Double) av).toPlainString());
                                } else if (av instanceof Float) {
                                    g.writeNumber(new BigDecimal((Float) av).toPlainString());
                                } else if (av instanceof Integer) {
                                    g.writeNumber(new BigDecimal((Integer) av).toPlainString());
                                } else {
                                    g.writeObject(av);
                                }
                                /*if (av instanceof Double)
                                g.writeNumber(new BigDecimal((Double) av));
                                else if (av instanceof Float)
                                g.writeNumber(new BigDecimal((Float) av));
                                else if (av instanceof Integer)
                                g.writeNumber((Integer) av);*/
                            }
                            g.writeEndArray();
                        }
                    } else {
                        g.writeObjectField(f.getName(), value);
                    }
                }

            } catch (IllegalAccessException e) {
                logger.warn("Could not get field: {}", f.getName(), e);
            }
        }
        g.writeEndObject();
    }
    if (logger.isDebugEnabled())
        logger.debug(writer.toString());
    return writer.toString();
}

From source file:gr.abiss.calipso.tiers.util.ModelContext.java

public static ModelContext from(Field field) {
    Class<?> domainClass = field.getType();
    if (Collection.class.isAssignableFrom(domainClass)) {
        domainClass = GenericCollectionTypeResolver.getCollectionFieldType(field);
    }//from  ww  w .ja v  a2  s . c o  m
    return from(domainClass);
}

From source file:edu.usu.sdl.openstorefront.core.util.EntityUtil.java

/**
 * This only support updating NON-composite keys.
 *
 * @param <T>//from  ww  w. ja  v  a  2  s. c  om
 * @param entity
 * @param value
 */
public static <T extends BaseEntity> void updatePKFieldValue(T entity, String value) {
    Field field = getPKField(entity);
    if (field != null) {
        if (isSubClass("BasePK", field.getType()) == false) {
            try {
                field.setAccessible(true);
                field.set(entity, value);
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                throw new OpenStorefrontRuntimeException(
                        "Unable to set value on " + entity.getClass().getName(), "Check entity passed in.");
            }
        } else {
            throw new OpenStorefrontRuntimeException(
                    "Set value on Composite PK is not supported. Entity:  " + entity.getClass().getName(),
                    "Check entity passed in.");
        }
    } else {
        throw new OpenStorefrontRuntimeException("Unable to find PK for enity: " + entity.getClass().getName(),
                "Check entity passed in.");
    }
}

From source file:com.madrobot.di.Converter.java

public static void storeValue(final JSONObject jsonObject, final String key, Object value, final Field field)
        throws JSONException {

    Class<?> classType = field.getType();

    if (clzTypeKeyMap.containsKey(classType)) {
        final int code = clzTypeKeyMap.get(classType);
        switch (code) {
        case TYPE_STRING:
        case TYPE_SHORT:
        case TYPE_INT:
        case TYPE_LONG:
        case TYPE_CHAR:
        case TYPE_FLOAT:
        case TYPE_DOUBLE:
            break;
        case TYPE_BOOLEAN:
            Boolean userValue = (Boolean) value;
            if (field.isAnnotationPresent(BooleanFormat.class)) {
                BooleanFormat formatAnnotation = field.getAnnotation(BooleanFormat.class);
                String trueFormat = formatAnnotation.trueFormat();
                String falseFormat = formatAnnotation.falseFormat();
                if (userValue) {
                    value = trueFormat;/*from  www  . j  a  va 2 s .  c  o  m*/
                } else {
                    value = falseFormat;
                }
            } else {
                value = userValue;
            }
            break;
        case TYPE_DATE:
            Date date = (Date) value;
            SimpleDateFormat simpleDateFormat = null;
            if (field.isAnnotationPresent(com.madrobot.di.wizard.json.annotations.DateFormat.class)) {
                com.madrobot.di.wizard.json.annotations.DateFormat formatAnnotation = field
                        .getAnnotation(com.madrobot.di.wizard.json.annotations.DateFormat.class);
                String dateFormat = formatAnnotation.format();
                simpleDateFormat = new SimpleDateFormat(dateFormat);
            } else {
                simpleDateFormat = new SimpleDateFormat();
            }
            value = simpleDateFormat.format(date);
            break;
        }
        jsonObject.put(key, value);
    }
}

From source file:com.github.juanmf.java2plant.Parser.java

protected static void addAggregation(Set<Relation> relations, Class<?> fromType, Field f) {
    Class<?> delegateType = f.getType();
    String varName = f.getName();
    String message = varName + ": " + TypesHelper.getSimpleName(f.getGenericType().toString());
    String toCardinal = "1";
    String toName = delegateType.getName();
    if (isMulti(delegateType)) {
        toCardinal = "*";
        if (!delegateType.isArray()) {
            Set<String> typeVars = getTypeParams(f);
            for (String type : typeVars) {
                Relation aggregation = new Aggregation(fromType, type, f, toCardinal, message);
                relations.add(aggregation);
            }//from  www . jav  a  2  s  . co m
            return;
        }
        toName = CanonicalName.getClassName(delegateType.getName());
    }
    Relation aggregation = new Aggregation(fromType, toName, f, toCardinal, message);
    relations.add(aggregation);
}

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

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(CurrentPrincipalIdPredicate.class)) {
            return currentPrincipalPredicateFactory;
        } else {//w w  w .  j  a v a  2 s. c o  m
            return anyToOnePredicateFactory;
        }
    } else {
        return factoryForClassMap.get(clazz);
    }
}

From source file:edu.mayo.cts2.framework.model.util.ModelUtils.java

public static ChangeableResource createChangeableResource(IsChangeable changeable) {
    ChangeableResource choice = new ChangeableResource();

    for (Field field : choice.getClass().getDeclaredFields()) {
        if (field.getType().equals(changeable.getClass()) || field.getName().equals("_choiceValue")) {
            field.setAccessible(true);/* w  ww. j  a  v a  2s. c  om*/
            try {
                field.set(choice, changeable);
            } catch (IllegalArgumentException e) {
                throw new IllegalStateException(e);
            } catch (IllegalAccessException e) {
                throw new IllegalStateException(e);
            }
        }
    }

    return choice;
}