Example usage for java.lang.reflect Field setInt

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

Introduction

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

Prototype

@CallerSensitive
@ForceInline 
public void setInt(Object obj, int i) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

Sets the value of a field as an int on the specified object.

Usage

From source file:org.syncany.plugins.transfer.TransferSettings.java

/**
 * Set the value of a field in the settings class.
 *
 * @param key The field name as it is used in the {@link TransferSettings}
 * @param value The object which should be the setting's value. The object's type must match the field type.
 *              {@link Integer}, {@link String}, {@link Boolean}, {@link File} and implementation of
 *              {@link TransferSettings} are converted.
 * @throws StorageException Thrown if the field either does not exist or isn't accessible or
 *         conversion failed due to invalid field types.
 *//*from   w  w w . ja v a 2s  . c  o  m*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public final void setField(String key, Object value) throws StorageException {
    try {
        Field[] elementFields = ReflectionUtil.getAllFieldsWithAnnotation(this.getClass(), Element.class);

        for (Field field : elementFields) {
            field.setAccessible(true);

            String fieldName = field.getName();
            Type fieldType = field.getType();

            if (key.equalsIgnoreCase(fieldName)) {
                if (value == null) {
                    field.set(this, null);
                } else if (fieldType == Integer.TYPE && (value instanceof Integer || value instanceof String)) {
                    field.setInt(this, Integer.parseInt(String.valueOf(value)));
                } else if (fieldType == Boolean.TYPE && (value instanceof Boolean || value instanceof String)) {
                    field.setBoolean(this, Boolean.parseBoolean(String.valueOf(value)));
                } else if (fieldType == String.class && value instanceof String) {
                    field.set(this, value);
                } else if (fieldType == File.class && value instanceof String) {
                    field.set(this, new File(String.valueOf(value)));
                } else if (ReflectionUtil.getClassFromType(fieldType).isEnum() && value instanceof String) {
                    Class<? extends Enum> enumClass = (Class<? extends Enum>) ReflectionUtil
                            .getClassFromType(fieldType);
                    String enumValue = String.valueOf(value).toUpperCase();

                    Enum translatedEnum = Enum.valueOf(enumClass, enumValue);
                    field.set(this, translatedEnum);
                } else if (TransferSettings.class.isAssignableFrom(value.getClass())) {
                    field.set(this, ReflectionUtil.getClassFromType(fieldType).cast(value));
                } else {
                    throw new RuntimeException("Invalid value type: " + value.getClass());
                }
            }
        }
    } catch (Exception e) {
        throw new StorageException("Unable to parse value because its format is invalid: " + e.getMessage(), e);
    }
}

From source file:wowhead_itemreader.WoWHeadData.java

private void setJsonValue(String fieldName, Object value, int type) {
    try {/*  w  w w . ja va2s  .  com*/
        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.alex73.skarynka.scan.Book2.java

private void set(Object obj, String fieldName, String value, String debug) {
    try {/*from  w ww  .  jav  a2 s  .c o m*/
        Field f = obj.getClass().getField(fieldName);
        if (!Modifier.isPublic(f.getModifiers()) || Modifier.isStatic(f.getModifiers())
                || Modifier.isTransient(f.getModifiers())) {
            errors.add("Field is not public for '" + debug + "'");
            return;
        }
        if (f.getType() == int.class) {
            f.setInt(obj, Integer.parseInt(value));
        } else if (f.getType() == boolean.class) {
            f.setBoolean(obj, Boolean.parseBoolean(value));
        } else if (f.getType() == String.class) {
            f.set(obj, value);
        } else if (Set.class.isAssignableFrom(f.getType())) {
            TreeSet<String> v = new TreeSet<>(Arrays.asList(value.split(";")));
            f.set(obj, v);
        } else {
            errors.add("Unknown field class for set '" + debug + "'");
            return;
        }
    } catch (NoSuchFieldException ex) {
        errors.add("Unknown field for set '" + debug + "'");
    } catch (IllegalAccessException ex) {
        errors.add("Wrong field for set '" + debug + "'");
    } catch (Exception ex) {
        errors.add("Error set value to field for '" + debug + "'");
    }
}

From source file:com.ferdi2005.secondgram.AndroidUtilities.java

public static void clearCursorDrawable(EditText editText) {
    if (editText == null) {
        return;//  w w  w .  ja  va 2  s. c om
    }
    try {
        Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
        mCursorDrawableRes.setAccessible(true);
        mCursorDrawableRes.setInt(editText, 0);
    } catch (Exception e) {
        FileLog.e(e);
    }
}

From source file:org.apache.cassandra.db.ScrubTest.java

/** The SecondaryIndex class is used for custom indexes so to avoid
 * making a public final field into a private field with getters
 * and setters, we resort to this hack in order to test it properly
 * since it can have two values which influence the scrubbing behavior.
 * @param comparator - the key comparator we want to test
 *//*  w  w  w . jav a2  s  .  c  o  m*/
private void setKeyComparator(AbstractType<?> comparator) {
    try {
        Field keyComparator = SecondaryIndex.class.getDeclaredField("keyComparator");
        keyComparator.setAccessible(true);
        int modifiers = keyComparator.getModifiers();
        Field modifierField = keyComparator.getClass().getDeclaredField("modifiers");
        modifiers = modifiers & ~Modifier.FINAL;
        modifierField.setAccessible(true);
        modifierField.setInt(keyComparator, modifiers);

        keyComparator.set(null, comparator);
    } catch (Exception ex) {
        fail("Failed to change key comparator in secondary index : " + ex.getMessage());
        ex.printStackTrace();
    }
}

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 a  v  a 2s  . c  om*/
            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: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()
 *//*  w  ww  . j a v  a  2s. c  o  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:org.wso2.carbon.identity.openidconnect.SAMLAssertionClaimsCallbackTest.java

private void setStaticField(Class classname, String fieldName, Object value)
        throws NoSuchFieldException, IllegalAccessException {
    Field declaredField = classname.getDeclaredField(fieldName);
    declaredField.setAccessible(true);//  w w w  .  j av  a 2 s. c  o m

    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(declaredField, declaredField.getModifiers() & ~Modifier.FINAL);

    declaredField.set(null, value);
}

From source file:com.adobe.cq.wcm.core.components.extension.contentfragment.internal.models.v1.ContentFragmentImplTest.java

@Before
public void setTestFixture() throws NoSuchFieldException, IllegalAccessException {
    cfmLogger = spy(LoggerFactory.getLogger("FakeLogger"));
    Field field = ContentFragmentImpl.class.getDeclaredField("LOG");
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    field.setAccessible(true);/*from  w w w. java 2  s. c o  m*/
    // remove final modifier from field

    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(null, cfmLogger);
}

From source file:org.wso2.carbon.apimgt.impl.AbstractAPIManagerTestCase.java

private static void setFinalStatic(Field field, Object newValue) throws Exception {
    field.setAccessible(true);/*from   w ww .j  a  va2 s.c om*/
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(null, newValue);
}