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:cn.org.once.cstack.cli.processor.LoggerPostProcessor.java

public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
    ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {

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

            if (field.getAnnotation(InjectLogger.class) != null && field.getType().equals(Logger.class)) {
                ReflectionUtils.makeAccessible(field);
                Logger logger = Logger.getLogger(bean.getClass().getName());

                field.set(bean, logger);

                StreamHandler fileHandler;
                try {

                    FileOutputStream fileOutputStream = new FileOutputStream(new File("errors.log"), true);
                    fileHandler = new StreamHandler(fileOutputStream, new SimpleFormatter());
                    fileHandler.setLevel(Level.SEVERE);
                    logger.addHandler(fileHandler);

                } catch (SecurityException | IOException e) {
                    throw new IllegalArgumentException(e);
                }//  ww w .  j  ava  2s. com

            }
        }
    });

    return bean;
}

From source file:com.epam.ta.reportportal.ws.validation.JaskonRequiredPropertiesValidator.java

@Override
public void validate(Object object, Errors errors) {
    for (Field field : collectFields(object.getClass())) {
        if (AnnotationUtils.isAnnotationDeclaredLocally(JsonInclude.class, field.getType())) {
            try {
                Object innerObject = Accessible.on(object).field(field).getValue();
                if (null != innerObject) {
                    errors.pushNestedPath(field.getName());
                    validate(innerObject, errors);
                }/*from w w w.ja  v  a  2s .  co m*/
            } catch (Exception e) {
                LOGGER.error("JaskonRequiredPropertiesValidator error: " + e.getMessage(), e);
                // do nothing
            }

        }
        if (field.isAnnotationPresent(JsonProperty.class)
                && field.getAnnotation(JsonProperty.class).required()) {
            String errorCode = new StringBuilder("NotNull.").append(field.getName()).toString();
            ValidationUtils.rejectIfEmpty(errors, field.getName(), errorCode, new Object[] { errorCode });
        }
    }
    if (errors.getNestedPath() != null && errors.getNestedPath().length() != 0) {
        errors.popNestedPath();
    }
}

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

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    Pair<Class<?>, Object> typeObjectPair = SpringUtil.checkForDinamicProxy(bean);
    Class<?> type = typeObjectPair.getLeft();
    Object target = typeObjectPair.getRight();

    try {// w ww .  j  a v  a  2s. co  m

        for (Field field : type.getDeclaredFields()) {
            if (field.isAnnotationPresent(LoadContent.class) && String.class.equals(field.getType())) {

                field.setAccessible(true);
                String fileName = getFileName(target, field);

                if (!StringUtils.isEmpty(fileName)) {
                    field.set(target, Util.loadContent(fileName));
                }
            }
        }
    } catch (Exception e) {
        throw new BeanInitializationException(e.getMessage(), e);
    }

    return bean;
}

From source file:com.shenit.commons.utils.GsonUtils.java

/**
 * ???./*from www .java  2  s  .  c  o  m*/
 * @param clazz
 * @return
 */
public static Field<?>[] serializeFields(Class<?> clazz) {
    if (REGISTERED_FIELDS.containsKey(clazz))
        return REGISTERED_FIELDS.get(clazz);
    java.lang.reflect.Field[] fields = clazz.getDeclaredFields();
    List<Field<?>> fs = Lists.newArrayList();
    SerializedName serializedName;
    JsonProperty jsonProp;
    IgnoreField ignore;
    for (java.lang.reflect.Field field : fields) {
        if (field == null)
            continue;
        serializedName = field.getAnnotation(SerializedName.class);
        jsonProp = field.getAnnotation(JsonProperty.class);
        ignore = field.getAnnotation(IgnoreField.class);
        if (ignore != null)
            continue;
        String name = null;
        if (serializedName != null) {
            name = serializedName.value();
        } else if (jsonProp != null) {
            name = jsonProp.value();
        } else {
            name = Modifier.isStatic(field.getModifiers()) ? null : field.getName();
        }
        if (name == null)
            continue;

        Default defVal = field.getDeclaredAnnotation(Default.class);
        fs.add(new Field(name, field.getName(), field.getType(), defVal == null ? null : defVal.value()));
    }
    Field<?>[] fsArray = fs.toArray(new Field<?>[0]);
    REGISTERED_FIELDS.put(clazz, fsArray);
    return fsArray;
}

From source file:net.minecraftforge.common.util.EnumHelper.java

@SuppressWarnings({ "unchecked", "serial" })
@Nullable/*from ww  w .ja v a 2 s .c o  m*/
private static <T extends Enum<?>> T addEnum(boolean test, final Class<T> enumType, @Nullable String enumName,
        final Class<?>[] paramTypes, @Nullable Object[] paramValues) {
    if (!isSetup) {
        setup();
    }

    Field valuesField = null;
    Field[] fields = enumType.getDeclaredFields();

    for (Field field : fields) {
        String name = field.getName();
        if (name.equals("$VALUES") || name.equals("ENUM$VALUES")) //Added 'ENUM$VALUES' because Eclipse's internal compiler doesn't follow standards
        {
            valuesField = field;
            break;
        }
    }

    int flags = (FMLForgePlugin.RUNTIME_DEOBF ? Modifier.PUBLIC : Modifier.PRIVATE) | Modifier.STATIC
            | Modifier.FINAL | 0x1000 /*SYNTHETIC*/;
    if (valuesField == null) {
        String valueType = String.format("[L%s;", enumType.getName().replace('.', '/'));

        for (Field field : fields) {
            if ((field.getModifiers() & flags) == flags
                    && field.getType().getName().replace('.', '/').equals(valueType)) //Apparently some JVMs return .'s and some don't..
            {
                valuesField = field;
                break;
            }
        }
    }

    if (valuesField == null) {
        final List<String> lines = Lists.newArrayList();
        lines.add(String.format("Could not find $VALUES field for enum: %s", enumType.getName()));
        lines.add(String.format("Runtime Deobf: %s", FMLForgePlugin.RUNTIME_DEOBF));
        lines.add(String.format("Flags: %s",
                String.format("%16s", Integer.toBinaryString(flags)).replace(' ', '0')));
        lines.add("Fields:");
        for (Field field : fields) {
            String mods = String.format("%16s", Integer.toBinaryString(field.getModifiers())).replace(' ', '0');
            lines.add(String.format("       %s %s: %s", mods, field.getName(), field.getType().getName()));
        }

        for (String line : lines)
            FMLLog.log.fatal(line);

        if (test) {
            throw new EnhancedRuntimeException("Could not find $VALUES field for enum: " + enumType.getName()) {
                @Override
                protected void printStackTrace(WrappedPrintStream stream) {
                    for (String line : lines)
                        stream.println(line);
                }
            };
        }
        return null;
    }

    if (test) {
        Object ctr = null;
        Exception ex = null;
        try {
            ctr = getConstructorAccessor(enumType, paramTypes);
        } catch (Exception e) {
            ex = e;
        }
        if (ctr == null || ex != null) {
            throw new EnhancedRuntimeException(
                    String.format("Could not find constructor for Enum %s", enumType.getName()), ex) {
                private String toString(Class<?>[] cls) {
                    StringBuilder b = new StringBuilder();
                    for (int x = 0; x < cls.length; x++) {
                        b.append(cls[x].getName());
                        if (x != cls.length - 1)
                            b.append(", ");
                    }
                    return b.toString();
                }

                @Override
                protected void printStackTrace(WrappedPrintStream stream) {
                    stream.println("Target Arguments:");
                    stream.println("    java.lang.String, int, " + toString(paramTypes));
                    stream.println("Found Constructors:");
                    for (Constructor<?> ctr : enumType.getDeclaredConstructors()) {
                        stream.println("    " + toString(ctr.getParameterTypes()));
                    }
                }
            };
        }
        return null;
    }

    valuesField.setAccessible(true);

    try {
        T[] previousValues = (T[]) valuesField.get(enumType);
        T newValue = makeEnum(enumType, enumName, previousValues.length, paramTypes, paramValues);
        setFailsafeFieldValue(valuesField, null, ArrayUtils.add(previousValues, newValue));
        cleanEnumCache(enumType);

        return newValue;
    } catch (Exception e) {
        FMLLog.log.error("Error adding enum with EnumHelper.", e);
        throw new RuntimeException(e);
    }
}

From source file:io.apiman.test.integration.runner.handlers.AbstractAnnotationHandler.java

/**
 * If possible assign value to given field
 *
 * @param field filed to be assigned to/*from   ww  w .j  a  v a2 s  .  co  m*/
 * @param value assigned value
 * @throws IllegalAccessException
 */
public <ValueType> void setField(Object target, Field field, Class<ValueType> valueType, ValueType value)
        throws IllegalAccessException {
    if (field.getType().isAssignableFrom(value.getClass())) {
        field.setAccessible(true);
        field.set(target, value);
    }
}

From source file:com.sap.csc.poc.ems.persistence.initial.entitlement.EntitlementHeaderAttributeDataInitializer.java

private <TEntitlementAttribute extends EntitlementAttribute> TEntitlementAttribute generateEntitlementAttributes(
        Field field, TEntitlementAttribute entitlementAttribute) {
    entitlementAttribute.setName(field.getName());
    entitlementAttribute.setType(field.getType().getSimpleName());
    entitlementAttribute.setLength(50);//from w w w .  jav  a 2  s  .c o  m
    entitlementAttribute.setValidation("NOT_NULL");
    return entitlementAttribute;
}

From source file:com.epam.ta.reportportal.database.search.CriteriaMap.java

private boolean isDynamicInnerFields(Field f) {
    return Map.class.isAssignableFrom(f.getType());
}

From source file:de.openknowledge.jaxrs.versioning.conversion.FieldVersionProperty.java

public FieldVersionProperty(Field field) {
    this.field = notNull(field);
    this.name = field.getName();
    this.type = field.getType();
}

From source file:by.creepid.docsreporter.context.meta.ImagesMetadataFiller.java

@Override
public void fillMetadata(FieldsMetadata metadataToFill, Class<?> modelClass, String modelName,
        Map<String, Class<?>> iterationNames) {
    Map<String, Field> fields = FieldHelper.getAnnotatedTypeArgumentFields(modelClass, modelName,
            imageAnnotation, true);//  www  .j a va2  s. c  om
    for (Field field : fields.values()) {

        String name = field.getName();
        if (field.getType() != byte[].class) {
            throw new IllegalStateException("Image field [" + name + "] must have byte array type!");
        }

        Image imageAnnot = (Image) field.getAnnotation(imageAnnotation);

        List<String> aliases = getAliases(field.getDeclaringClass(), iterationNames);
        if (!aliases.isEmpty()) {
            for (String alias : aliases) {

                String[] bookmarks = imageAnnot.bookmarks();
                for (String bookmark : bookmarks) {

                    metadataToFill.addFieldAsImage(bookmark, FieldHelper.getFieldPath(alias, field.getName()));
                }
            }
        } else {
            String[] bookmarks = imageAnnot.bookmarks();
            for (String bookmark : bookmarks) {

                metadataToFill.addFieldAsImage(bookmark,
                        FieldHelper.getFieldPath(field.getDeclaringClass().getSimpleName(), field.getName()),
                        behaviour);
            }
        }
    }

    Map<String, Field> fieldMap = FieldHelper.getAnnotatedDeclaredFields(modelClass, modelName, imageAnnotation,
            true);
    Set<Map.Entry<String, Field>> entries = fieldMap.entrySet();
    for (Map.Entry<String, Field> entry : entries) {
        Image imageAnnot = (Image) entry.getValue().getAnnotation(imageAnnotation);

        String[] bookmarks = imageAnnot.bookmarks();
        for (String bookmark : bookmarks) {
            metadataToFill.addFieldAsImage(bookmark, entry.getKey(), behaviour);
        }

    }
}