Example usage for java.lang.reflect Field setDouble

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

Introduction

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

Prototype

@CallerSensitive
@ForceInline 
public void setDouble(Object obj, double d) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

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

Usage

From source file:org.sonar.api.checks.AnnotationCheckFactory.java

private void configureField(Object check, Field field, String value) {
    try {//  www  .java2s .  com
        field.setAccessible(true);

        if (field.getType().equals(String.class)) {
            field.set(check, value);

        } else if ("int".equals(field.getType().getSimpleName())) {
            field.setInt(check, Integer.parseInt(value));

        } else if ("short".equals(field.getType().getSimpleName())) {
            field.setShort(check, Short.parseShort(value));

        } else if ("long".equals(field.getType().getSimpleName())) {
            field.setLong(check, Long.parseLong(value));

        } else if ("double".equals(field.getType().getSimpleName())) {
            field.setDouble(check, Double.parseDouble(value));

        } else if ("boolean".equals(field.getType().getSimpleName())) {
            field.setBoolean(check, Boolean.parseBoolean(value));

        } else if ("byte".equals(field.getType().getSimpleName())) {
            field.setByte(check, Byte.parseByte(value));

        } else if (field.getType().equals(Integer.class)) {
            field.set(check, Integer.parseInt(value));

        } else if (field.getType().equals(Long.class)) {
            field.set(check, Long.parseLong(value));

        } else if (field.getType().equals(Double.class)) {
            field.set(check, Double.parseDouble(value));

        } else if (field.getType().equals(Boolean.class)) {
            field.set(check, Boolean.parseBoolean(value));

        } else {
            throw new SonarException(
                    "The type of the field " + field + " is not supported: " + field.getType());
        }
    } catch (IllegalAccessException e) {
        throw new SonarException(
                "Can not set the value of the field " + field + " in the class: " + check.getClass().getName(),
                e);
    }
}

From source file:wowhead_itemreader.WoWHeadData.java

private void setJsonValue(String fieldName, Object value, int type) {
    try {/*from   w  w w.j  a va2 s .  co  m*/
        Class<? extends WoWHeadData> aClass = this.getClass();
        Field field = aClass.getDeclaredField(fieldName);
        if (value != null) {
            try {
                switch (type) {
                case 1:
                    field.setInt(this, Integer.parseInt(value.toString()));
                    break;
                case 2:
                    field.setDouble(this, Double.parseDouble(value.toString()));
                    break;
                default:
                    field.set(this, value.toString());
                    break;
                }
            } catch (Exception ex) {
            }
        }
    } catch (NoSuchFieldException ex) {
        Logger.getLogger(WoWHeadData.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(WoWHeadData.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.sonar.api.checks.checkers.AnnotationCheckerFactory.java

private void configureField(Object checker, Field field, Map.Entry<String, String> parameter)
        throws IllegalAccessException {
    field.setAccessible(true);/*from   w w w. j a v  a  2s. co m*/

    if (field.getType().equals(String.class)) {
        field.set(checker, parameter.getValue());

    } else if (field.getType().getSimpleName().equals("int")) {
        field.setInt(checker, Integer.parseInt(parameter.getValue()));

    } else if (field.getType().getSimpleName().equals("short")) {
        field.setShort(checker, Short.parseShort(parameter.getValue()));

    } else if (field.getType().getSimpleName().equals("long")) {
        field.setLong(checker, Long.parseLong(parameter.getValue()));

    } else if (field.getType().getSimpleName().equals("double")) {
        field.setDouble(checker, Double.parseDouble(parameter.getValue()));

    } else if (field.getType().getSimpleName().equals("boolean")) {
        field.setBoolean(checker, Boolean.parseBoolean(parameter.getValue()));

    } else if (field.getType().getSimpleName().equals("byte")) {
        field.setByte(checker, Byte.parseByte(parameter.getValue()));

    } else if (field.getType().equals(Integer.class)) {
        field.set(checker, new Integer(Integer.parseInt(parameter.getValue())));

    } else if (field.getType().equals(Long.class)) {
        field.set(checker, new Long(Long.parseLong(parameter.getValue())));

    } else if (field.getType().equals(Double.class)) {
        field.set(checker, new Double(Double.parseDouble(parameter.getValue())));

    } else if (field.getType().equals(Boolean.class)) {
        field.set(checker, Boolean.valueOf(Boolean.parseBoolean(parameter.getValue())));

    } else {
        throw new UnvalidCheckerException(
                "The type of the field " + field + " is not supported: " + field.getType());
    }
}

From source file:me.henrytao.observableorm.orm.ObservableModel.java

public T deserialize(Map<String, Object> map) throws IllegalAccessException {
    Field[] fields = getDeclaredFields();
    for (Field f : fields) {
        if (!f.isAnnotationPresent(Column.class)) {
            continue;
        }/*from w w w  . ja va2  s .  c  o m*/
        Column column = f.getAnnotation(Column.class);
        if (!column.deserialize()) {
            continue;
        }
        f.setAccessible(true);
        String name = column.name();
        Object value = map.get(name);
        Class type = f.getType();
        Deserializer deserializer = deserializerMap.get(type);
        if (deserializer != null) {
            f.set(this, deserializer.deserialize(value));
        } else if (boolean.class.isAssignableFrom(type)) {
            f.setBoolean(this, value == null ? false : (Boolean) value);
        } else if (double.class.isAssignableFrom(type)) {
            f.setDouble(this, value == null ? 0.0 : (Double) value);
        } else if (float.class.isAssignableFrom(type)) {
            f.setFloat(this, value == null ? 0f : (Float) value);
        } else if (int.class.isAssignableFrom(type)) {
            f.setInt(this, value == null ? 0 : (int) value);
        } else if (short.class.isAssignableFrom(type)) {
            f.setShort(this, value == null ? 0 : (short) value);
        } else if (byte.class.isAssignableFrom(type)) {
            f.setByte(this, value == null ? 0 : (byte) value);
        } else if (String.class.isAssignableFrom(type)) {
            f.set(this, value);
        } else if (JSONObject.class.isAssignableFrom(type)) {
            // todo: nested object should be another model
        }
    }
    return (T) this;
}

From source file:com.trafficspaces.api.model.Resource.java

public void setJSONObject(JSONObject jsonObject) {
    Iterator itr = jsonObject.keys();
    while (itr.hasNext()) {
        String key = (String) itr.next();
        Object value = jsonObject.opt(key);

        try {/*from   ww w.  j  av a  2  s  . c o m*/
            Field field = this.getClass().getField(key);
            Class type = field.getType();

            int fieldModifiers = field.getModifiers();
            //System.out.println("key=" + key + ", name=" + field.getName() + ", value=" + value + ", type=" +type + ", componentType=" +type.getComponentType() + 
            //      ", ispublic="+Modifier.isPublic(fieldModifiers) + ", isstatic="+Modifier.isStatic(fieldModifiers) + ", isnative="+Modifier.isNative(fieldModifiers) +
            //      ", isprimitive="+type.isPrimitive() + ", isarray="+type.isArray() + ", isResource="+Resource.class.isAssignableFrom(type));

            if (type.isPrimitive()) {
                if (type.equals(int.class)) {
                    field.setInt(this, jsonObject.getInt(key));
                } else if (type.equals(double.class)) {
                    field.setDouble(this, jsonObject.getDouble(key));
                }
            } else if (type.isArray()) {
                JSONArray jsonArray = null;
                if (value instanceof JSONArray) {
                    jsonArray = (JSONArray) value;
                } else if (value instanceof JSONObject) {
                    JSONObject jsonSubObject = (JSONObject) value;
                    jsonArray = jsonSubObject.optJSONArray(key.substring(0, key.length() - 1));
                }
                if (jsonArray != null && jsonArray.length() > 0) {
                    Class componentType = type.getComponentType();
                    Object[] values = (Object[]) Array.newInstance(componentType, jsonArray.length());
                    for (int j = 0; j < jsonArray.length(); j++) {
                        Resource resource = (Resource) componentType.newInstance();
                        resource.setJSONObject(jsonArray.getJSONObject(j));
                        values[j] = resource;
                    }
                    field.set(this, values);
                }
            } else if (Resource.class.isAssignableFrom(type) && value instanceof JSONObject) {
                Resource resource = (Resource) type.newInstance();
                resource.setJSONObject((JSONObject) value);
                field.set(this, resource);
            } else if (type.equals(String.class) && value instanceof String) {
                field.set(this, (String) value);
            }
        } catch (NoSuchFieldException nsfe) {
            System.err.println("warning: field does not exist. key=" + key + ",value=" + value);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("error: key=" + key + ",value=" + value + ", error=" + e.getMessage());
        }
    }
}

From source file:com.qmetry.qaf.automation.data.BaseDataBean.java

protected void setField(Field field, String val) {
    try {/*from w w w.j  a  v a 2s.  c o  m*/
        // deal with IllegalAccessException
        field.setAccessible(true);
        if (field.getType() == String.class) {
            field.set(this, val);
        } else {
            Method setter = null;
            try {
                setter = this.getClass().getMethod("set" + StringUtil.getTitleCase(field.getName()),
                        String.class);
            } catch (Exception e) {

            }
            if (null != setter) {
                setter.setAccessible(true);
                setter.invoke(this, val);
            } else if (field.getType() == Integer.TYPE) {
                field.setInt(this, Integer.parseInt(val));
            } else if (field.getType() == Float.TYPE) {
                field.setFloat(this, Float.parseFloat(val));

            } else if (field.getType() == Double.TYPE) {
                field.setDouble(this, Double.parseDouble(val));

            } else if (field.getType() == Long.TYPE) {
                field.setLong(this, Long.parseLong(val));

            } else if (field.getType() == Boolean.TYPE) {
                Boolean bval = StringUtils.isBlank(val) ? null
                        : NumberUtils.isNumber(val) ? (Integer.parseInt(val) != 0)
                                : Boolean.parseBoolean(val) || val.equalsIgnoreCase("T")
                                        || val.equalsIgnoreCase("Y") || val.equalsIgnoreCase("YES");

                field.setBoolean(this, bval);

            } else if (field.getType() == Short.TYPE) {
                field.setShort(this, Short.parseShort(val));
            } else if (field.getType() == Date.class) {
                Date dVal = null;
                try {
                    dVal =

                            StringUtils.isBlank(val) ? null
                                    : NumberUtils.isNumber(val) ? DateUtil.getDate(Integer.parseInt(val))
                                            : DateUtil.parseDate(val, "MM/dd/yyyy");
                } catch (ParseException e) {
                    logger.error("Expected date in MM/dd/yyyy format.", e);
                }
                field.set(this, dVal);
            }
        }
    } catch (IllegalArgumentException e) {
        logger.error("Unable to fill random data in field " + field.getName(), e);
    } catch (IllegalAccessException e) {
        logger.error("Unable to Access " + field.getName(), e);
    } catch (InvocationTargetException e) {
        logger.error("Unable to invoke setter for " + field.getName(), e);
    }

}

From source file:lineage2.gameserver.Config.java

/**
 * Method setField./*  www . j  av a 2s  .co m*/
 * @param fieldName String
 * @param value String
 * @return boolean
 */
public static boolean setField(String fieldName, String value) {
    Field field = FieldUtils.getField(Config.class, fieldName);
    if (field == null) {
        return false;
    }
    try {
        if (field.getType() == boolean.class) {
            field.setBoolean(null, BooleanUtils.toBoolean(value));
        } else if (field.getType() == int.class) {
            field.setInt(null, NumberUtils.toInt(value));
        } else if (field.getType() == long.class) {
            field.setLong(null, NumberUtils.toLong(value));
        } else if (field.getType() == double.class) {
            field.setDouble(null, NumberUtils.toDouble(value));
        } else if (field.getType() == String.class) {
            field.set(null, value);
        } else {
            return false;
        }
    } catch (IllegalArgumentException e) {
        return false;
    } catch (IllegalAccessException e) {
        return false;
    }
    return true;
}

From source file:com.sikulix.core.SX.java

private static void setOptions(PropertiesConfiguration someOptions) {
    if (isNull(someOptions) || someOptions.size() == 0) {
        return;/* w w w  .  ja v  a 2 s .  c o m*/
    }
    Iterator<String> allKeys = someOptions.getKeys();
    List<String> sxSettings = new ArrayList<>();
    while (allKeys.hasNext()) {
        String key = allKeys.next();
        if (key.startsWith("Settings.")) {
            sxSettings.add(key);
            continue;
        }
        trace("!setOptions: %s = %s", key, someOptions.getProperty(key));
    }
    if (sxSettings.size() > 0) {
        Class cClass = null;
        try {
            cClass = Class.forName("org.sikuli.basics.Settings");
        } catch (ClassNotFoundException e) {
            error("!setOptions: %s", cClass);
        }
        if (!isNull(cClass)) {
            for (String sKey : sxSettings) {
                String sAttr = sKey.substring("Settings.".length());
                Field cField = null;
                Class ccField = null;
                try {
                    cField = cClass.getField(sAttr);
                    ccField = cField.getType();
                    if (ccField.getName() == "boolean") {
                        cField.setBoolean(null, someOptions.getBoolean(sKey));
                    } else if (ccField.getName() == "int") {
                        cField.setInt(null, someOptions.getInt(sKey));
                    } else if (ccField.getName() == "float") {
                        cField.setFloat(null, someOptions.getFloat(sKey));
                    } else if (ccField.getName() == "double") {
                        cField.setDouble(null, someOptions.getDouble(sKey));
                    } else if (ccField.getName() == "String") {
                        cField.set(null, someOptions.getString(sKey));
                    }
                    trace("!setOptions: %s = %s", sAttr, someOptions.getProperty(sKey));
                    someOptions.clearProperty(sKey);
                } catch (Exception ex) {
                    error("!setOptions: %s = %s", sKey, sxOptions.getProperty(sKey));
                }
            }
        }
    }
}

From source file:cern.c2mon.shared.common.datatag.address.impl.HardwareAddressImpl.java

/**
 * Create a HardwareAddress object from its XML representation.
 *
 * @param pElement DOM element containing the XML representation of a HardwareAddress object, as created by the
 *                 toConfigXML() method.
 * @throws RuntimeException if unable to instantiate the Hardware address
 * @see cern.c2mon.shared.common.datatag.address.HardwareAddress#toConfigXML()
 *//*from   www  . j av a 2  s  .  co m*/
public final synchronized HardwareAddress fromConfigXML(Element pElement) {
    Class hwAddressClass = null;
    HardwareAddressImpl hwAddress = null;

    try {
        hwAddressClass = Class.forName(pElement.getAttribute("class"));
        hwAddress = (HardwareAddressImpl) hwAddressClass.newInstance();
    } catch (ClassNotFoundException cnfe) {
        cnfe.printStackTrace();
        throw new RuntimeException("Exception caught when instantiating a hardware address from XML", cnfe);
    } catch (IllegalAccessException iae) {
        iae.printStackTrace();
        throw new RuntimeException("Exception caught when instantiating a hardware address from XML", iae);
    } catch (InstantiationException ie) {
        ie.printStackTrace();
        throw new RuntimeException("Exception caught when instantiating a hardware address from XML", ie);
    }

    NodeList fields = pElement.getChildNodes();
    Node fieldNode = null;
    int fieldsCount = fields.getLength();
    String fieldName;
    String fieldValueString;
    String fieldTypeName = "";

    for (int i = 0; i < fieldsCount; i++) {
        fieldNode = fields.item(i);
        if (fieldNode.getNodeType() == Node.ELEMENT_NODE) {
            fieldName = fieldNode.getNodeName();

            if (fieldNode.getFirstChild() != null) {
                fieldValueString = fieldNode.getFirstChild().getNodeValue();
            } else {
                fieldValueString = "";
            }
            try {
                Field field = hwAddressClass.getDeclaredField(decodeFieldName(fieldName));
                fieldTypeName = field.getType().getName();

                if (fieldTypeName.equals("short")) {
                    field.setShort(hwAddress, Short.parseShort(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Short")) {
                    field.set(hwAddress, new Integer(Integer.parseInt(fieldValueString)));
                } else if (fieldTypeName.equals("int")) {
                    field.setInt(hwAddress, Integer.parseInt(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Integer")) {
                    field.set(hwAddress, new Integer(Integer.parseInt(fieldValueString)));
                } else if (fieldTypeName.equals("float")) {
                    field.setFloat(hwAddress, Float.parseFloat(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Float")) {
                    field.set(hwAddress, new Float(Float.parseFloat(fieldValueString)));
                } else if (fieldTypeName.equals("double")) {
                    field.setDouble(hwAddress, Double.parseDouble(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Double")) {
                    field.set(hwAddress, new Double(Double.parseDouble(fieldValueString)));
                } else if (fieldTypeName.equals("long")) {
                    field.setLong(hwAddress, Long.parseLong(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Long")) {
                    field.set(hwAddress, new Long(Long.parseLong(fieldValueString)));
                } else if (fieldTypeName.equals("byte")) {
                    field.setByte(hwAddress, Byte.parseByte(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Byte")) {
                    field.set(hwAddress, new Byte(Byte.parseByte(fieldValueString)));
                } else if (fieldTypeName.equals("char")) {
                    field.setChar(hwAddress, fieldValueString.charAt(0));
                } else if (fieldTypeName.equals("java.lang.Character")) {
                    field.set(hwAddress, new Character(fieldValueString.charAt(0)));
                } else if (fieldTypeName.equals("boolean")) {
                    field.setBoolean(hwAddress, Boolean.getBoolean(fieldValueString));
                } else if (fieldTypeName.equals("java.lang.Boolean")) {
                    field.set(hwAddress, new Boolean(Boolean.getBoolean(fieldValueString)));
                } else if (fieldTypeName.equals("java.util.HashMap")) {
                    field.set(hwAddress, SimpleXMLParser.domNodeToMap(fieldNode));
                } else if (field.getType().isEnum()) {
                    Object[] enumConstants = field.getType().getEnumConstants();
                    for (Object enumConstant : enumConstants) {
                        if (enumConstant.toString().equals(fieldValueString)) {
                            field.set(hwAddress, enumConstant);
                        }
                    }
                } else {
                    field.set(hwAddress, fieldValueString);
                }
            } catch (NoSuchFieldException nsfe) {
                String errorMsg = "fromConfigXML(...) - Error occured while parsing XML <HardwareAddress> tag. "
                        + "The following variable does not exist in " + hwAddressClass.toString() + ": \""
                        + decodeFieldName(fieldName) + "\"";
                log.error(errorMsg);
                throw new IllegalArgumentException(errorMsg);
            } catch (IllegalAccessException iae) {
                iae.printStackTrace();
                throw new RuntimeException(iae);
            } catch (NumberFormatException npe) {
                String errorMsg = "fromConfigXML(...) - Error occured while parsing XML <HardwareAddress> tag. Field \""
                        + fieldName + "\" shall not be empty since we expect a \"" + fieldTypeName
                        + "\" value. Please correct the XML configuration for " + hwAddressClass.toString();
                log.error(errorMsg);
                throw new IllegalArgumentException(errorMsg);
            }
        }
    }
    return hwAddress;
}

From source file:com.nonninz.robomodel.RoboModel.java

private void loadField(Field field, Cursor query) throws DatabaseNotUpToDateException {
    final Class<?> type = field.getType();
    final boolean wasAccessible = field.isAccessible();
    final int columnIndex = query.getColumnIndex(field.getName());
    field.setAccessible(true);/*  w w w . j  av a2 s . c o m*/

    /*
     * TODO: There is the potential of a problem here:
     * What happens if the developer changes the type of a field between releases?
     *
     * If he saves first, then the column type will be changed (In the future).
     * If he loads first, we don't know if an Exception will be thrown if the
     * types are incompatible, because it's undocumented in the Cursor documentation.
     */

    try {
        if (type == String.class) {
            field.set(this, query.getString(columnIndex));
        } else if (type == Boolean.TYPE) {
            final boolean value = query.getInt(columnIndex) == 1 ? true : false;
            field.setBoolean(this, value);
        } else if (type == Byte.TYPE) {
            field.setByte(this, (byte) query.getShort(columnIndex));
        } else if (type == Double.TYPE) {
            field.setDouble(this, query.getDouble(columnIndex));
        } else if (type == Float.TYPE) {
            field.setFloat(this, query.getFloat(columnIndex));
        } else if (type == Integer.TYPE) {
            field.setInt(this, query.getInt(columnIndex));
        } else if (type == Long.TYPE) {
            field.setLong(this, query.getLong(columnIndex));
        } else if (type == Short.TYPE) {
            field.setShort(this, query.getShort(columnIndex));
        } else if (type.isEnum()) {
            final String string = query.getString(columnIndex);
            if (string != null && string.length() > 0) {
                final Object[] constants = type.getEnumConstants();
                final Method method = type.getMethod("valueOf", Class.class, String.class);
                final Object value = method.invoke(constants[0], type, string);
                field.set(this, value);
            }
        } else {
            // Try to de-json it (db column must be of type text)
            try {
                final Object value = mMapper.readValue(query.getString(columnIndex), field.getType());
                field.set(this, value);
            } catch (final Exception e) {
                final String msg = String.format("Type %s is not supported for field %s", type,
                        field.getName());
                Ln.w(e, msg);
                throw new IllegalArgumentException(msg);
            }
        }
    } catch (final IllegalAccessException e) {
        final String msg = String.format("Field %s is not accessible", type, field.getName());
        throw new IllegalArgumentException(msg);
    } catch (final NoSuchMethodException e) {
        // Should not happen
        throw new RuntimeException(e);
    } catch (final InvocationTargetException e) {
        // Should not happen
        throw new RuntimeException(e);
    } catch (IllegalStateException e) {
        // This is when there is no column in db, but there is in the model
        throw new DatabaseNotUpToDateException(e);
    } finally {
        field.setAccessible(wasAccessible);
    }
}