Example usage for java.lang.reflect Field setFloat

List of usage examples for java.lang.reflect Field setFloat

Introduction

In this page you can find the example usage for java.lang.reflect Field setFloat.

Prototype

@CallerSensitive
@ForceInline 
public void setFloat(Object obj, float f) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

Sets the value of a field as a float on the specified object.

Usage

From source file:org.j2free.admin.ReflectionMarshaller.java

/**
 * /* w  ww  .  j a va 2s.c  om*/
 * @param entity
 * @param parameterMap
 * @param controller
 * @return
 * @throws MarshallingException
 */
public Object marshallIn(Object entity, Map<String, String[]> parameterMap, Controller controller)
        throws MarshallingException {
    Field field;
    Converter converter;
    Method setter;
    String[] newValues;

    log.debug("Marshalling in instance of " + entity.getClass().getSimpleName());

    boolean error = false, success = false, isEntity = false, isCollection = false;

    Class collectionType;
    Class fieldType;

    for (Map.Entry<Field, Converter> ent : instructions.entrySet()) {

        // reset flags
        error = success = isEntity = isCollection = false;

        field = ent.getKey();
        converter = ent.getValue();

        if (converter.isReadOnly()) {
            log.debug("Skipping read-only field " + field.getName());
            continue;
        }

        newValues = parameterMap.get(field.getName());

        if (newValues == null || newValues.length == 0) {
            log.debug("Skipping field " + field.getName() + ", no new value set.");
            continue;
        }

        isEntity = converter.isEntity();
        isCollection = converter.isCollection();

        fieldType = field.getType();
        collectionType = isCollection ? converter.getType() : null;

        log.debug("Marshalling in field " + field.getName());

        // try to get the original value
        try {
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            if (field.isAccessible()) {
                log.debug(field.getName() + " is accessible");
                if (!isEntity && !isCollection) {

                    log.debug("!isEntity && !isCollection");

                    // if it's an array, it needs special treatment
                    if (fieldType.isArray()) {
                        log.debug(field.getName() + " is an Array");

                        Class arrayType = fieldType.getComponentType();

                        // If we can, just convert with a cast()
                        if (arrayType.isAssignableFrom(String.class)) {
                            log.debug(arrayType.getName() + " is assignable from String.class");

                            Object[] newArray = new Object[newValues.length];
                            for (int i = 0; i < newValues.length; i++) {
                                newArray[i] = arrayType.cast(newValues[i]);
                            }
                            field.set(entity, newArray);

                        } else {

                            if (isInteger(fieldType)) {

                                Integer[] newArray = new Integer[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Integer.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isFloat(fieldType)) {

                                Float[] newArray = new Float[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Float.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isDouble(fieldType)) {

                                Double[] newArray = new Double[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Double.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isShort(fieldType)) {

                                Short[] newArray = new Short[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Short.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isChar(fieldType)) {

                                field.set(entity, ServletUtils.join(newValues, "").toCharArray());

                            } else if (isLong(fieldType)) {

                                Long[] newArray = new Long[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Long.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isBoolean(fieldType)) {

                                Boolean[] newArray = new Boolean[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Boolean.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isByte(fieldType)) {

                                Byte[] newArray = new Byte[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Byte.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else {
                                throw new MarshallingException(
                                        "Don't know how to marshall an array of a non-primitive, and non-assignable type! field = "
                                                + field.getName());
                            }
                        }

                    } else {

                        // Check out if it's assignable via a straight cast,
                        // that could save time
                        if (fieldType.isAssignableFrom(String.class)) {
                            log.debug(fieldType.getName() + " is assignable from String.class");
                            // this might throw an exception, but we're going
                            // to ignore it because there are other ways of
                            // setting the value if this doesn't work.
                            try {
                                field.set(entity, fieldType.cast(newValues[0]));
                                log.debug("Assigned via cast");
                            } catch (Exception e) {
                                log.debug("Error setting field by cast", e);
                            }
                            success = true;
                        }

                        // if it wasn't assignable via a straight cast, try
                        // working around it.
                        if (!success) {
                            if (isInteger(fieldType) && !newValues[0].equals("")) {
                                field.setInt(entity, Integer.valueOf(newValues[0]));
                            } else if (isFloat(fieldType) && !newValues[0].equals("")) {
                                field.setFloat(entity, Float.valueOf(newValues[0]));
                            } else if (isDouble(fieldType) && !newValues[0].equals("")) {
                                field.setDouble(entity, Double.valueOf(newValues[0]));
                            } else if (isShort(fieldType) && !newValues[0].equals("")) {
                                field.setShort(entity, Short.valueOf(newValues[0]));
                            } else if (isChar(fieldType)) {
                                field.setChar(entity, newValues[0].charAt(0));
                            } else if (isLong(fieldType) && !newValues[0].equals("")) {
                                field.setLong(entity, Long.valueOf(newValues[0]));
                            } else if (isBoolean(fieldType) && !newValues[0].equals("")) {
                                field.setBoolean(entity, Boolean.valueOf(newValues[0]));
                            } else if (isByte(fieldType) && !newValues[0].equals("")) {
                                field.setByte(entity, Byte.valueOf(newValues[0]));
                            } else if (isDate(fieldType)) {
                                if (newValues[0].equals("")) {
                                    field.set(entity, null);
                                } else {
                                    try {
                                        field.set(entity, asDate(newValues[0]));
                                    } catch (ParseException pe) {
                                        log.warn("Error parsing date: " + newValues[0], pe);
                                    }
                                }
                            } else if (!newValues[0].equals("")) {
                                log.debug("Not sure how to set " + field.getName() + " of type "
                                        + fieldType.getName() + ", attemping cast.");
                                field.set(entity, fieldType.cast(newValues[0]));
                            } else if (newValues[0].equals("")) {
                                log.debug("Skipping field " + field.getName()
                                        + ", empty string value passed in.");
                            }
                        }
                    }

                } else if (isEntity && !isCollection) {

                    log.debug("isEntity && !isCollection");

                    ReflectionMarshaller innerMarshaller = ReflectionMarshaller.getForClass(fieldType);
                    field.set(entity, controller.proxy(fieldType, innerMarshaller.asIdType(newValues[0])));

                } else if (!isEntity && isCollection) {

                    log.debug("!isEntity && isCollection");

                    throw new MarshallingException("Error, collections of non-entities are not yet supported.");

                } else if (isEntity && isCollection) {

                    log.debug("isEntity && isCollection");

                    // for now, this is going to expect the parameter to be a
                    // comma-delimited string of entity ids
                    String[] idsString = newValues[0].toString().split(",");
                    Collection collection = (Collection) field.get(entity);

                    log.debug("newValues.length = " + newValues.length);
                    log.debug("newValues[0] = " + newValues[0]);
                    log.debug("idsString.length = " + idsString.length);

                    if (collection == null)
                        collection = new LinkedList();

                    collection.clear();

                    if (idsString.length > 0) {

                        ReflectionMarshaller collectionMarshaller = ReflectionMarshaller
                                .getForClass(collectionType);

                        log.debug("CollectionType = " + collectionType.getName());

                        for (String idString : idsString) {
                            if (idString.equals("")) {
                                log.debug("Skipping empty idString");
                                continue;
                            }
                            collection.add(
                                    controller.proxy(collectionType, collectionMarshaller.asIdType(idString)));
                        }

                    }

                    field.set(entity, collection);
                }
            } else {
                error = true;
            }
        } catch (IllegalAccessException iae) {
            log.error("Unable to set " + field.getName() + " directly.", iae);
            error = true;
        } catch (ClassCastException cce) {
            log.error("Error setting " + field.getName() + ".", cce);
            error = true;
        }

        // if we hit an error getting it directly, try via the getter
        if (error) {
            error = false;
            try {
                setter = converter.getSetter();
                if (setter != null) {
                    if (!setter.isAccessible()) {
                        setter.setAccessible(true);
                    }
                    if (setter.isAccessible()) {
                        if (!isEntity && !isCollection) {

                            // if it's an array, it needs special treatment
                            if (fieldType.isArray()) {
                                log.debug(field.getName() + " is an Array");

                                Class arrayType = fieldType.getComponentType();

                                // If we can, just convert with a cast()
                                if (arrayType.isAssignableFrom(String.class)) {
                                    log.debug(arrayType.getName() + " is assignable from String.class");

                                    Object[] newArray = new Object[newValues.length];
                                    for (int i = 0; i < newValues.length; i++) {
                                        newArray[i] = arrayType.cast(newValues[i]);
                                    }
                                    setter.invoke(entity, newArray);

                                } else {

                                    if (isInteger(fieldType)) {

                                        Integer[] newArray = new Integer[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Integer.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isFloat(fieldType)) {

                                        Float[] newArray = new Float[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Float.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isDouble(fieldType)) {

                                        Double[] newArray = new Double[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Double.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isShort(fieldType)) {

                                        Short[] newArray = new Short[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Short.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isChar(fieldType)) {

                                        setter.invoke(entity, ServletUtils.join(newValues, "").toCharArray());

                                    } else if (isLong(fieldType)) {

                                        Long[] newArray = new Long[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Long.valueOf(newValues[i]);
                                        }
                                        field.set(entity, (Object[]) newArray);

                                    } else if (isBoolean(fieldType)) {

                                        Boolean[] newArray = new Boolean[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Boolean.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isByte(fieldType)) {

                                        Byte[] newArray = new Byte[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Byte.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else {
                                        throw new MarshallingException(
                                                "Don't know how to marshall an array of a non-primitive, and non-assignable type! field = "
                                                        + field.getName());
                                    }
                                }

                            } else {
                                // Check out if it's assignable via a straight cast,
                                // that could save time
                                if (fieldType.isAssignableFrom(String.class)) {
                                    log.debug(fieldType.getName() + " is assignable from String.class");
                                    // this might throw an exception, but we're going
                                    // to ignore it because there are other ways of
                                    // setting the value if this doesn't work.
                                    try {
                                        setter.invoke(entity, fieldType.cast(newValues[0]));
                                    } catch (Exception e) {
                                        log.debug("Error setting field by cast", e);
                                    }
                                    success = true;
                                }

                                // if it wasn't assignable via a straight cast, try
                                // working around it.
                                if (!success) {
                                    if (isInteger(fieldType)) {
                                        setter.invoke(entity, Integer.valueOf(newValues[0]));
                                    } else if (isFloat(fieldType)) {
                                        setter.invoke(entity, Float.valueOf(newValues[0]));
                                    } else if (isDouble(fieldType)) {
                                        setter.invoke(entity, Double.valueOf(newValues[0]));
                                    } else if (isShort(fieldType)) {
                                        setter.invoke(entity, Short.valueOf(newValues[0]));
                                    } else if (isChar(fieldType)) {
                                        setter.invoke(entity, newValues[0].charAt(0));
                                    } else if (isLong(fieldType)) {
                                        setter.invoke(entity, Long.valueOf(newValues[0]));
                                    } else if (isBoolean(fieldType)) {
                                        setter.invoke(entity, Boolean.valueOf(newValues[0]));
                                    } else if (isByte(fieldType)) {
                                        setter.invoke(entity, Byte.valueOf(newValues[0]));
                                    } else if (isDate(fieldType)) {
                                        if (newValues[0].equals("")) {
                                            field.set(entity, null);
                                        } else {
                                            try {
                                                setter.invoke(entity, asDate(newValues[0]));
                                            } catch (ParseException pe) {
                                                log.warn("Error parsing date: " + newValues[0], pe);
                                            }
                                        }
                                    } else {
                                        log.debug("Not sure how to set " + field.getName() + " of type "
                                                + fieldType.getName() + ", attemping cast.");
                                        setter.invoke(entity, fieldType.cast(newValues[0]));
                                    }
                                }
                            }

                        } else if (isEntity && !isCollection) {

                            ReflectionMarshaller innerMarshaller = ReflectionMarshaller.getForClass(fieldType);
                            setter.invoke(entity,
                                    controller.proxy(fieldType, innerMarshaller.asIdType(newValues[0])));

                        } else if (!isEntity && isCollection) {

                            throw new MarshallingException(
                                    "Error, collections of non-entities are not yet supported.");

                        } else if (isEntity && isCollection) {
                            // for now, this is going to expect the parameter to be a
                            // comma-delimited string of entity ids
                            String[] idsString = newValues[0].toString().split(",");
                            Collection collection = (Collection) field.get(entity);

                            if (collection == null)
                                collection = new LinkedList();

                            if (idsString.length == 0 && collection.isEmpty())
                                continue;

                            collection.clear();

                            if (idsString.length > 0) {

                                ReflectionMarshaller collectionMarshaller = ReflectionMarshaller
                                        .getForClass(collectionType);

                                for (String idString : idsString) {
                                    if (idString.equals("")) {
                                        log.debug("Skipping empty idString");
                                        continue;
                                    }
                                    collection.add(controller.proxy(collectionType,
                                            collectionMarshaller.asIdType(idString)));
                                }
                            }

                            setter.invoke(entity, collection);
                        }
                    } else {
                        error = true;
                    }
                } else {
                    error = true;
                }
            } catch (IllegalAccessException iae) {
                log.error("Error accessing setter", iae);
                error = true;
            } catch (InvocationTargetException ite) {
                log.error("Error invoking setter", ite);
                error = true;
            }
        }

        if (error) {
            throw new MarshallingException("Unable to marshall in field " + field.getName() + ".");
        }
    }
    return entity;
}

From source file:au.com.addstar.cellblock.configuration.AutoConfig.java

@SuppressWarnings("unchecked")
public boolean load() {
    FileConfiguration yml = new YamlConfiguration();
    try {//from   ww w.  j  a  va 2  s  .  c  o m
        if (mFile.getParentFile().exists() || mFile.getParentFile().mkdirs()) {// Make sure the file exists
            if (mFile.exists() || mFile.createNewFile()) {
                // Parse the config
                yml.load(mFile);
                for (Field field : getClass().getDeclaredFields()) {
                    ConfigField configField = field.getAnnotation(ConfigField.class);
                    if (configField == null)
                        continue;

                    String optionName = configField.name();
                    if (optionName.isEmpty())
                        optionName = field.getName();

                    field.setAccessible(true);

                    String path = (configField.category().isEmpty() ? "" : configField.category() + ".") //$NON-NLS-2$
                            + optionName;
                    if (!yml.contains(path)) {
                        if (field.get(this) == null)
                            throw new InvalidConfigurationException(
                                    path + " is required to be set! Info:\n" + configField.comment());
                    } else {
                        // Parse the value

                        if (field.getType().isArray()) {
                            // Integer
                            if (field.getType().getComponentType().equals(Integer.TYPE))
                                field.set(this, yml.getIntegerList(path).toArray(new Integer[0]));

                            // Float
                            else if (field.getType().getComponentType().equals(Float.TYPE))
                                field.set(this, yml.getFloatList(path).toArray(new Float[0]));

                            // Double
                            else if (field.getType().getComponentType().equals(Double.TYPE))
                                field.set(this, yml.getDoubleList(path).toArray(new Double[0]));

                            // Long
                            else if (field.getType().getComponentType().equals(Long.TYPE))
                                field.set(this, yml.getLongList(path).toArray(new Long[0]));

                            // Short
                            else if (field.getType().getComponentType().equals(Short.TYPE))
                                field.set(this, yml.getShortList(path).toArray(new Short[0]));

                            // Boolean
                            else if (field.getType().getComponentType().equals(Boolean.TYPE))
                                field.set(this, yml.getBooleanList(path).toArray(new Boolean[0]));

                            // String
                            else if (field.getType().getComponentType().equals(String.class)) {
                                field.set(this, yml.getStringList(path).toArray(new String[0]));
                            } else
                                throw new IllegalArgumentException("Cannot use type "
                                        + field.getType().getSimpleName() + " for AutoConfiguration"); //$NON-NLS-1$
                        } else if (List.class.isAssignableFrom(field.getType())) {
                            if (field.getGenericType() == null)
                                throw new IllegalArgumentException(
                                        "Cannot use type List without specifying generic type for AutoConfiguration");

                            Type type = ((ParameterizedType) field.getGenericType())
                                    .getActualTypeArguments()[0];

                            if (type.equals(Integer.class))
                                field.set(this, newList((Class<? extends List<Integer>>) field.getType(),
                                        yml.getIntegerList(path)));
                            else if (type.equals(Float.class))
                                field.set(this, newList((Class<? extends List<Float>>) field.getType(),
                                        yml.getFloatList(path)));
                            else if (type.equals(Double.class))
                                field.set(this, newList((Class<? extends List<Double>>) field.getType(),
                                        yml.getDoubleList(path)));
                            else if (type.equals(Long.class))
                                field.set(this, newList((Class<? extends List<Long>>) field.getType(),
                                        yml.getLongList(path)));
                            else if (type.equals(Short.class))
                                field.set(this, newList((Class<? extends List<Short>>) field.getType(),
                                        yml.getShortList(path)));
                            else if (type.equals(Boolean.class))
                                field.set(this, newList((Class<? extends List<Boolean>>) field.getType(),
                                        yml.getBooleanList(path)));
                            else if (type.equals(String.class))
                                field.set(this, newList((Class<? extends List<String>>) field.getType(),
                                        yml.getStringList(path)));
                            else
                                throw new IllegalArgumentException(
                                        "Cannot use type " + field.getType().getSimpleName() + "<" //$NON-NLS-2$
                                                + type.toString() + "> for AutoConfiguration");
                        } else if (Set.class.isAssignableFrom(field.getType())) {
                            if (field.getGenericType() == null)
                                throw new IllegalArgumentException(
                                        "Cannot use type set without specifying generic type for AytoConfiguration");

                            Type type = ((ParameterizedType) field.getGenericType())
                                    .getActualTypeArguments()[0];

                            if (type.equals(Integer.class))
                                field.set(this, newSet((Class<? extends Set<Integer>>) field.getType(),
                                        yml.getIntegerList(path)));
                            else if (type.equals(Float.class))
                                field.set(this, newSet((Class<? extends Set<Float>>) field.getType(),
                                        yml.getFloatList(path)));
                            else if (type.equals(Double.class))
                                field.set(this, newSet((Class<? extends Set<Double>>) field.getType(),
                                        yml.getDoubleList(path)));
                            else if (type.equals(Long.class))
                                field.set(this, newSet((Class<? extends Set<Long>>) field.getType(),
                                        yml.getLongList(path)));
                            else if (type.equals(Short.class))
                                field.set(this, newSet((Class<? extends Set<Short>>) field.getType(),
                                        yml.getShortList(path)));
                            else if (type.equals(Boolean.class))
                                field.set(this, newSet((Class<? extends Set<Boolean>>) field.getType(),
                                        yml.getBooleanList(path)));
                            else if (type.equals(String.class))
                                field.set(this, newSet((Class<? extends Set<String>>) field.getType(),
                                        yml.getStringList(path)));
                            else
                                throw new IllegalArgumentException(
                                        "Cannot use type " + field.getType().getSimpleName() + "<" //$NON-NLS-2$
                                                + type.toString() + "> for AutoConfiguration");
                        } else {
                            // Integer
                            if (field.getType().equals(Integer.TYPE))
                                field.setInt(this, yml.getInt(path));

                            // Float
                            else if (field.getType().equals(Float.TYPE))
                                field.setFloat(this, (float) yml.getDouble(path));

                            // Double
                            else if (field.getType().equals(Double.TYPE))
                                field.setDouble(this, yml.getDouble(path));

                            // Long
                            else if (field.getType().equals(Long.TYPE))
                                field.setLong(this, yml.getLong(path));

                            // Short
                            else if (field.getType().equals(Short.TYPE))
                                field.setShort(this, (short) yml.getInt(path));

                            // Boolean
                            else if (field.getType().equals(Boolean.TYPE))
                                field.setBoolean(this, yml.getBoolean(path));

                            // ItemStack
                            else if (field.getType().equals(ItemStack.class))
                                field.set(this, yml.getItemStack(path));

                            // String
                            else if (field.getType().equals(String.class))
                                field.set(this, yml.getString(path));
                            else
                                throw new IllegalArgumentException("Cannot use type "
                                        + field.getType().getSimpleName() + " for AutoConfiguration"); //$NON-NLS-1$
                        }
                    }
                }

                onPostLoad();
            } else {
                Bukkit.getLogger().log(Level.INFO, "Unable to create file: " + mFile.toString());
            }
        } else {
            Bukkit.getLogger().log(Level.INFO, "Unable to create file: " + mFile.getParentFile().toString());
        }
        return true;
    } catch (IOException | InvalidConfigurationException | IllegalAccessException
            | IllegalArgumentException e) {
        e.printStackTrace();
        return false;
    }
}