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:ch.silviowangler.dox.AutomaticTranslatorAdvice.java

private void translate(Translatable translatable) {

    logger.debug("Detected translatable in class {}", translatable.getClass().getName());

    final String messageKey = translatable.retrieveMessageKey();
    final Locale locale = LocaleContextHolder.getLocale();
    try {/* ww  w  .j  a v a 2 s  .  c  o m*/
        String translation = translationService.findTranslation(messageKey, locale);
        translatable.setTranslation(translation);
    } catch (NoTranslationFoundException e) {
        String message = getTranslation(messageKey, locale);
        translatable.setTranslation(message);
    }

    final Field[] declaredFields = translatable.getClass().getDeclaredFields();

    for (Field field : declaredFields) {
        if (isTranslatable(field.getType())) {
            try {
                Translatable objectToTranslate = (Translatable) new PropertyDescriptor(field.getName(),
                        translatable.getClass()).getReadMethod().invoke(translatable);
                if (objectToTranslate != null) {
                    translate(objectToTranslate);
                }
            } catch (IllegalAccessException | IntrospectionException | InvocationTargetException e) {
                logger.error("Unable to translate", e);
            }
        }
    }
}

From source file:in.hatimi.nosh.support.CmdLineManager.java

private boolean injectProperties(Object target, Field field, Properties values) {
    if (!field.getType().isAssignableFrom(Properties.class)) {
        return false;
    }//from  w w w .  jav a  2  s  .  c o  m
    return injectImpl(target, field, values);
}

From source file:com.agileapes.couteau.context.spring.event.impl.AbstractMappedEventsTranslationScheme.java

@Override
public ApplicationEvent translate(Event originalEvent) throws EventTranslationException {
    final Class<? extends ApplicationEvent> eventClass;
    try {/*  w ww .j  a v a 2s  .  c  om*/
        eventClass = getTargetEvent(originalEvent.getClass());
    } catch (ClassNotFoundException e) {
        throw new EventTranslationException("Failed to locate target class for event", e);
    }
    final ApplicationEvent applicationEvent;
    try {
        applicationEvent = eventClass.getConstructor(Object.class).newInstance(originalEvent.getSource());
    } catch (Exception e) {
        throw new EventTranslationException(
                "Failed to instantiate event from " + eventClass.getCanonicalName());
    }
    for (Method method : originalEvent.getClass().getMethods()) {
        if (!GenericTranslationScheme.isGetter(method)) {
            continue;
        }
        final String fieldName = StringUtils
                .uncapitalize(method.getName().substring(method.getName().startsWith("get") ? 3 : 2));
        final Field field = ReflectionUtils.findField(eventClass, fieldName);
        if (field == null || !field.getType().isAssignableFrom(method.getReturnType())) {
            continue;
        }
        field.setAccessible(true);
        try {
            field.set(applicationEvent, method.invoke(originalEvent));
        } catch (Exception e) {
            throw new EventTranslationException("Failed to set property: " + fieldName, e);
        }
    }
    return applicationEvent;
}

From source file:org.jdal.ui.bind.DirectFieldAccessor.java

@Override
public Class<?> getPropertyType(String propertyName) throws BeansException {
    Field field = this.fieldMap.get(propertyName);
    if (field != null) {
        return field.getType();
    }//w w  w.j  a  v  a  2s  .c  om
    return null;
}

From source file:mercury.RootJsonHandler.java

protected <T extends DTO> T populateDtoFromJson(String jsonData, T dto) {
    try {/*from  w  w w .j  av a  2s  . co m*/
        JSONObject json = new JSONObject(jsonData);
        Class clazz = dto.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            try {
                String name = field.getName();
                Class fieldClass = field.getType();
                Object value = null;
                if (fieldClass.equals(String.class)) {
                    value = json.has(name) ? json.getString(name) : null;
                } else if (fieldClass.equals(Integer.class)) {
                    try {
                        value = json.has(name) ? json.getInt(name) : null;
                    } catch (Exception e) {
                        value = -1;
                    }
                } else if (fieldClass.equals(Float.class)) {
                    String sValue = json.has(name) ? json.getString(name).replaceAll(",", ".") : null;
                    value = sValue != null ? Float.valueOf(sValue) : null;
                } else if (fieldClass.equals(Date.class)) {
                    value = json.has(name) ? json.getString(name) : null;
                    value = value != null ? this.dateFormatter.parse((String) value) : null;
                }

                if (value == null) {
                    continue;
                }

                Method setter = clazz.getDeclaredMethod("set" + StringUtils.capitalize(name), fieldClass);
                if (setter != null) {
                    setter.invoke(dto, value);
                }
            } catch (Exception e) {
                continue;
            }
        }
    } catch (JSONException je) {
    }
    return dto;
}

From source file:me.xiaopan.android.gohttp.requestobject.RequestParser.java

/**
 * ?/*from w  w w. ja  v a 2s.  com*/
 * @param request 
 */
@SuppressWarnings("unchecked")
public static org.apache.http.Header[] parseRequestHeaders(Request request) {
    List<org.apache.http.Header> finalHeaders = null;
    for (Field field : getFields(request.getClass(), true, true, true)) {
        field.setAccessible(true);
        if (field.getAnnotation(Header.class) != null) { //???
            try {
                Object value = field.get(request);
                if (value != null) {
                    if (org.apache.http.Header.class.isAssignableFrom(field.getType())) { //?
                        if (finalHeaders == null) {
                            finalHeaders = new LinkedList<org.apache.http.Header>();
                        }
                        finalHeaders.add((org.apache.http.Header) value);
                    } else if (isArrayByType(field, org.apache.http.Header.class)) { //Header
                        org.apache.http.Header[] headers = (org.apache.http.Header[]) value;
                        for (org.apache.http.Header header : headers) {
                            if (header != null) {
                                if (finalHeaders == null) {
                                    finalHeaders = new LinkedList<org.apache.http.Header>();
                                }
                                finalHeaders.add(header);
                            }
                        }
                    } else if (isCollectionByType(field, Collection.class, org.apache.http.Header.class)) { //Header?
                        if (finalHeaders == null) {
                            finalHeaders = new LinkedList<org.apache.http.Header>();
                        }
                        finalHeaders.addAll((Collection<org.apache.http.Header>) value);
                    }
                }
            } catch (IllegalAccessException e1) {
                e1.printStackTrace();
            } catch (IllegalArgumentException e1) {
                e1.printStackTrace();
            }
        }
    }

    if (finalHeaders != null && finalHeaders.size() > 0) {
        org.apache.http.Header[] heades = new org.apache.http.Header[finalHeaders.size()];
        finalHeaders.toArray(heades);
        return heades;
    } else {
        return null;
    }
}

From source file:com.impetus.kundera.metadata.processor.relation.ManyToOneRelationMetadataProcessor.java

@Override
public void addRelationIntoMetadata(Field relationField, EntityMetadata metadata) {
    // taking field's type as foreign entity, ignoring "targetEntity"
    Class<?> targetEntity = relationField.getType();

    ManyToOne ann = relationField.getAnnotation(ManyToOne.class);
    Relation relation = new Relation(relationField, targetEntity, null, ann.fetch(),
            Arrays.asList(ann.cascade()), ann.optional(), null, // mappedBy is null
            Relation.ForeignKey.MANY_TO_ONE);

    boolean isJoinedByFK = relationField.isAnnotationPresent(JoinColumn.class);

    if (relationField.isAnnotationPresent(AssociationOverride.class)) {
        AssociationOverride annotation = relationField.getAnnotation(AssociationOverride.class);
        JoinColumn[] joinColumns = annotation.joinColumns();

        relation.setJoinColumnName(joinColumns[0].name());

    } else if (isJoinedByFK) {
        JoinColumn joinColumnAnn = relationField.getAnnotation(JoinColumn.class);
        relation.setJoinColumnName(//from   ww  w  . j ava  2 s.  c  o  m
                StringUtils.isBlank(joinColumnAnn.name()) ? relationField.getName() : joinColumnAnn.name());
    } else {
        relation.setJoinColumnName(relationField.getName());
    }

    relation.setBiDirectionalField(metadata.getEntityClazz());
    metadata.addRelation(relationField.getName(), relation);

}

From source file:org.jboss.arquillian.warp.extension.spring.container.SpringWarpTestEnricher.java

/**
 * {@inheritDoc}//from   ww w.  ja va2 s. com
 */
@Override
public void enrich(Object testCase) {

    // gets the collection of the annotated attributes
    List<Field> annotatedFields = SecurityActions.getFieldsWithAnnotation(testCase.getClass(),
            SpringMvcResource.class);

    // retrieves the captured execution context
    SpringMvcResult mvcResult = getSpringMvcResult();

    try {
        for (Field field : annotatedFields) {
            Object value = null;

            if (mvcResult != null) {
                if (field.getType() == SpringMvcResult.class) {
                    value = mvcResult;
                } else if (field.getType() == ModelAndView.class) {
                    value = mvcResult.getModelAndView();
                } else if (field.getType() == Exception.class) {
                    value = mvcResult.getException();
                } else if (field.getType() == HandlerInterceptor[].class) {
                    value = mvcResult.getInterceptors();
                } else if (field.getType() == Errors.class) {
                    value = mvcResult.getErrors();
                } else if (mvcResult.getHandler() != null
                        && field.getType() == mvcResult.getHandler().getClass()) {
                    value = mvcResult.getHandler();
                }
            }

            field.set(testCase, value);
        }
    } catch (Exception e) {
        throw new RuntimeException("Could not inject field in the test class.", e);
    }

}

From source file:org.apache.airavata.db.AbstractThriftDeserializer.java

/**
 * Generates a {@link JavaType} that matches the target Thrift field represented by the provided
 * {@code <E>} enumerated value.  If the field's type includes generics, the generics will
 * be added to the generated {@link JavaType} to support proper conversion.
 * @param thriftInstance The Thrift-generated class instance that will be converted to/from JSON.
 * @param field A {@code <E>} enumerated value that represents a field in a Thrift-based entity.
 * @return The {@link JavaType} representation of the type associated with the field.
 * @throws NoSuchFieldException if unable to determine the field's type.
 * @throws SecurityException if unable to determine the field's type.
 *//*  w  w w .j av a2 s. c  o m*/
protected JavaType generateValueType(final T thriftInstance, final E field)
        throws NoSuchFieldException, SecurityException {
    final TypeFactory typeFactory = TypeFactory.defaultInstance();

    final Field declaredField = thriftInstance.getClass().getDeclaredField(field.getFieldName());
    if (declaredField.getType().equals(declaredField.getGenericType())) {
        log.debug("Generating JavaType for type '{}'.", declaredField.getType());
        return typeFactory.constructType(declaredField.getType());
    } else {
        final ParameterizedType type = (ParameterizedType) declaredField.getGenericType();
        final Class<?>[] parameterizedTypes = new Class<?>[type.getActualTypeArguments().length];
        for (int i = 0; i < type.getActualTypeArguments().length; i++) {
            parameterizedTypes[i] = (Class<?>) type.getActualTypeArguments()[i];
        }
        log.debug("Generating JavaType for type '{}' with generics '{}'", declaredField.getType(),
                parameterizedTypes);
        return typeFactory.constructParametricType(declaredField.getType(), parameterizedTypes);
    }
}

From source file:com.github.tddts.jet.config.spring.postprocessor.MessageAnnotationBeanPostProcessor.java

private boolean checkField(Field field, Class<?> type) {
    if (!field.isAnnotationPresent(Message.class)) {
        return false;
    }/*from w  w  w  .ja va 2 s .c  o m*/
    if (field.getType().equals(String.class)) {
        return true;
    }
    logger.warn("Field [" + type + "." + field.getName()
            + "] is not populated with message. Should be a String field.");
    return false;
}