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:management.limbr.test.util.PojoTester.java

private void testGetter(Method getter, Field field) {
    Object testValue = getTestValueFor(field.getType());
    ReflectionTestUtils.setField(pojo, field.getName(), testValue);
    try {/*from  w w w.j a v  a2s. c  om*/
        assertEquals(getter.invoke(pojo), testValue);
    } catch (IllegalAccessException | InvocationTargetException ex) {
        fail("Couldn't access POJO's getter " + getter.getName(), ex);
    }
}

From source file:management.limbr.test.util.PojoTester.java

private void testSetter(Method setter, Field field) {
    Object testValue = getTestValueFor(field.getType());
    try {//from w ww  .j  av  a 2  s  .  c  o  m
        setter.invoke(pojo, testValue);
    } catch (IllegalAccessException | InvocationTargetException ex) {
        fail("Couldn't access POJO's setter " + setter.getName(), ex);
    }
    assertEquals(ReflectionTestUtils.getField(pojo, field.getName()), testValue);
}

From source file:io.github.benas.projector.processors.AbstractAnnotationProcessor.java

/**
 * Convert the value to field type and set it in the target object.
 *
 * @param target the target object/*from  w  ww . j a va2s .  co m*/
 * @param field the annotated field
 * @param key the annotation property attribute
 * @param value the value to inject
 * @throws Exception thrown if an exception occurs when trying to set the field value
 */
protected void injectProperty(Object target, Field field, String key, Object value) throws Exception {

    Object typedValue = ConvertUtils.convert(value, field.getType());
    try {
        PropertyUtils.setProperty(target, field.getName(), typedValue);
    } catch (Exception e) {
        throw new Exception("Unable to set property " + key + " on field " + field.getName() + " of type "
                + target.getClass() + ". A setter may be missing for this field.", e);
    }

}

From source file:com.bacoder.parser.core.DumpVisitor.java

@Override
public void visitBefore(Node node) {
    String tag = String.format("%s<%s sl=\"%d\" sc=\"%d\" el=\"%d\" ec=\"%d\">\n",
            Strings.repeat(indent, level), node.getClass().getSimpleName(), node.getStartLine(),
            node.getStartColumn(), node.getEndLine(), node.getEndColumn());
    try {//w ww . ja  v a  2s.c o m
        outputStream.write(tag.getBytes());

        Class<? extends Node> clazz = node.getClass();
        if (clazz.getAnnotation(DumpTextWithToString.class) != null) {
            String property = String.format("%s<text>%s</text>\n", Strings.repeat(indent, level + 1),
                    node.toString());
            try {
                outputStream.write(property.getBytes());
            } catch (IOException e) {
                throw new RuntimeException("Unable to write \'" + property + "\'", e);
            }
        } else {
            Field[] fields = node.getClass().getDeclaredFields();
            for (Field field : fields) {
                Class<?> type = field.getType();
                if (type.isPrimitive() || type.isEnum() || String.class.isAssignableFrom(type)) {
                    String propertyName = field.getName();
                    Object value;
                    try {
                        value = PropertyUtils.getSimpleProperty(node, propertyName);
                        String property = String.format("%s<%s>%s</%s>\n", Strings.repeat(indent, level + 1),
                                propertyName,
                                value == null ? "" : StringEscapeUtils.escapeXml(value.toString()),
                                propertyName);
                        try {
                            outputStream.write(property.getBytes());
                        } catch (IOException e) {
                            throw new RuntimeException("Unable to write \'" + property + "\'", e);
                        }
                    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                        // Ignore the field.
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Unable to write \'" + tag + "\'", e);
    }
    level++;
}

From source file:com.github.braully.web.DescriptorHtmlEntity.java

DescriptorHtmlEntity buildDescriptorHtmlEntity(Field field) {
    String ltype = field.getType().getSimpleName();
    ltype = ltype.substring(0, 1).toLowerCase() + ltype.substring(1);
    String lproperty = field.getName();
    String lpattern = null;// ww w .ja  v a  2s. c o  m
    if (field.getAnnotation(OneToOne.class) != null || field.getAnnotation(ManyToOne.class) != null) {
        lpattern = ltype;
        ltype = "entity";
    }
    if (field.getType().isAssignableFrom(Collection.class) && (field.getAnnotation(ManyToMany.class) != null
            || field.getAnnotation(OneToMany.class) != null)) {
        lpattern = ltype;
        ltype = "collection";
    }
    String llabel = lproperty.replaceAll("(\\p{Ll})(\\p{Lu})", "$1 $2");
    llabel = WordUtils.capitalize(llabel);

    DescriptorHtmlEntity he = new DescriptorHtmlEntity();
    he.classe = field.getType();
    he.type = ltype;
    he.property = lproperty;
    he.label = llabel;
    he.pattern = lpattern;
    return he;
}

From source file:adalid.core.XS1.java

static Object initialiseField(Object declaringObject, Field declaringField) {
    if (declaringObject == null || declaringField == null) {
        return null;
    }//w  w  w. j av a  2 s .  com
    String declaringFieldName = declaringField.getName();
    Class<?> declaringFieldType = declaringField.getType();
    if (NamedValue.class.equals(declaringFieldType)) {
        return NamedValueCache.getInstance(declaringFieldName);
    }
    String fieldName = declaringFieldName;
    Class<?> fieldType = getFieldType(declaringFieldType);
    if (fieldType == null) {
        return null;
    }
    Object instance = null;
    Class<?> declaringClass = declaringObject.getClass();
    Class<?> enclosingClass = fieldType.getEnclosingClass();
    boolean memberClass = fieldType.isMemberClass();
    Entity declaringEntity = declaringObject instanceof Entity ? (Entity) declaringObject : null;
    Artifact declaringArtifact = declaringObject instanceof Artifact ? (Artifact) declaringObject : null;
    boolean declaringArtifactIsParameter = false;
    if (declaringObject instanceof DataArtifact) {
        DataArtifact declaringDataArtifact = (DataArtifact) declaringObject;
        declaringArtifactIsParameter = declaringDataArtifact.isParameter();
    }
    String errmsg = "failed to create a new instance of field " + declaringField + " at " + declaringObject;
    try {
        CastingField castingFieldAnnotation = getCastingFieldAnnotation(declaringField, fieldType);
        if (castingFieldAnnotation != null) {
            String name = castingFieldAnnotation.value();
            Field field = getFieldToBeCasted(true, fieldName, name, declaringClass, fieldType);
            if (field != null) {
                errmsg = "failed to set casting field " + declaringField + " at " + declaringObject;
                instance = field.get(declaringObject);
                //                  if (instance == null) {
                //                      logFieldErrorMessage(fieldName, name, declaringClass, field, "field " + name + " is not allocated");
                //                  }
            }
        } else if (memberClass && enclosingClass != null && enclosingClass.isAssignableFrom(declaringClass)) {
            if (Operation.class.isAssignableFrom(fieldType)) {
                if (declaringArtifact == null) {
                    instance = fieldType.getConstructor(enclosingClass).newInstance(declaringObject);
                } else if (declaringEntity == null) {
                    TLC.setDeclaringArtifact(declaringArtifact);
                    instance = fieldType.getConstructor(enclosingClass).newInstance(declaringObject);
                    TLC.removeDeclaringArtifact();
                } else {
                    String key = fieldType.getSimpleName();
                    Map<String, Class<?>> map = declaringEntity.getOperationClassesMap();
                    Class<?> fieldTypeX = map.containsKey(key) ? map.get(key) : fieldType;
                    Class<?> enclosingClassX = fieldTypeX.getEnclosingClass();
                    TLC.setDeclaringArtifact(declaringArtifact);
                    instance = fieldTypeX.getConstructor(enclosingClassX).newInstance(declaringObject);
                    TLC.removeDeclaringArtifact();
                }
            } else {
                instance = fieldType.getConstructor(enclosingClass).newInstance(declaringObject);
            }
        } else if (enclosingClass == null) {
            if (Entity.class.isAssignableFrom(fieldType)) {
                if (declaringArtifact == null) {
                    instance = fieldType.newInstance();
                } else {
                    //                      Method method = fieldType.getMethod(GET_INSTANCE, new Class<?>[]{Artifact.class});
                    //                      instance = method.invoke(null, declaringObject);
                    Class<?> type = getTrueType(fieldType);
                    checkAbstractClassReference(declaringField, type);
                    String path = declaringArtifact.getClassPath();
                    int depth = declaringArtifact.depth() + 1;
                    int round = round(type, declaringArtifact);
                    TLC.getProject().getParser().setMaxDepthReached(depth);
                    TLC.getProject().getParser().setMaxRoundReached(round);
                    FieldAllocationSettings settings = new FieldAllocationSettings(declaringField,
                            declaringObject, depth, round);
                    int maxDepth = settings.getMaxDepth();
                    int maxRound = settings.getMaxRound();
                    String method1 = "allocate(maxDepth={0}, maxRound={1})";
                    String method2 = MessageFormat.format(method1, maxDepth, maxRound);
                    String remark1 = "maxDepth<" + depth;
                    String remark2 = "maxRound<" + round;
                    String pattern;
                    String remarks;
                    if (declaringArtifactIsParameter || declaringArtifact.depth() == 0
                            || (depth <= maxDepth && round <= maxRound)) {
                        TLC.getProject().getParser().track(depth, round, path, type, fieldName, method2, null);
                        instance = type.getConstructor(Artifact.class, Field.class).newInstance(declaringObject,
                                declaringField);
                        TLC.getProject().getParser().increaseEntityCount();
                    } else {
                        pattern = "{1}, {0} not allocated";
                        if (depth > maxDepth) {
                            remarks = MessageFormat.format(pattern, fieldName, remark1);
                            TLC.getProject().getParser().alert(depth, round, path, type, fieldName, method2,
                                    remarks);
                        }
                        if (round > maxRound) {
                            remarks = MessageFormat.format(pattern, fieldName, remark2);
                            TLC.getProject().getParser().alert(depth, round, path, type, fieldName, method2,
                                    remarks);
                        }
                    }
                }
            } else {
                instance = fieldType.newInstance();
            }
        }
        if (instance instanceof AbstractArtifact) {
            // do not declare here; it will be declared at the corresponding finalise method
            AbstractArtifact abstractArtifact = (AbstractArtifact) instance;
            abstractArtifact.setName(fieldName);
            abstractArtifact.setDeclaringArtifact(declaringArtifact);
            abstractArtifact.setDeclaringField(declaringField);
            if (instance instanceof VariantX) {
                VariantX variantX = (VariantX) instance;
                variantX.setDataType(declaringFieldType);
            }
        }
    } catch (IllegalArgumentException | IllegalAccessException | InstantiationException | NoSuchMethodException
            | InvocationTargetException ex) {
        throw new InstantiationRuntimeException(errmsg, ex);
    }
    return instance;
}

From source file:com.khubla.cbean.serializer.impl.json.JSONArrayFieldSerializer.java

@Override
public String serialize(Object o, Field field) throws SerializerException {
    try {/*from w w  w . j a v  a2s .c om*/
        final Class<?> componentType = field.getType().getComponentType();
        if (componentType.isPrimitive()) {
            final String[] values = BeanUtils.getArrayProperty(o, field.getName());
            final JSONArray jsonArray = new JSONArray(values);
            return jsonArray.toString();
        } else {
            final CBean<Object> cBean = CBeanServer.getInstance().getCBean(componentType);
            final Object[] values = (Object[]) PropertyUtils.getProperty(o, field.getName());
            final JSONArray jsonArray = new JSONArray();
            if (null != values) {
                for (int i = 0; i < values.length; i++) {
                    cBean.save(values[i]);
                    jsonArray.put(i, cBean.getId(values[i]));
                }
            }
            return jsonArray.toString();
        }
    } catch (final Exception e) {
        throw new SerializerException(e);
    }
}

From source file:springfox.documentation.spring.web.readers.parameter.ExpandedParameterBuilder.java

private AllowableValues allowableValues(final Field field) {

    AllowableValues allowable = null;//from w w  w.j a v  a  2 s  .c  om
    if (field.getType().isEnum()) {
        allowable = new AllowableListValues(getEnumValues(field.getType()), "LIST");
    }

    return allowable;
}

From source file:com.tasktop.c2c.server.common.service.tests.http.MultiUserClientHttpRequestFactoryTest.java

private HttpClient getHttpClient(ClientHttpRequest request) {
    Class<?> clazz = request.getClass();
    while (clazz != Object.class) {
        for (Field field : clazz.getDeclaredFields()) {
            if (HttpClient.class.isAssignableFrom(field.getType())) {
                field.setAccessible(true);
                try {
                    return (HttpClient) field.get(request);
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }/*from ww w .jav a  2 s  .  c  o  m*/
            }
        }
        clazz = clazz.getSuperclass();
    }
    throw new IllegalStateException();
}

From source file:jease.cmf.service.Serializer.java

public void registerConverter(Field field) {
    xstream.registerLocalConverter(field.getDeclaringClass(), field.getName(),
            field.getType().isArray() ? nodeArrayConverter : nodeConverter);
}