Example usage for java.lang.reflect Field setLong

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

Introduction

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

Prototype

@CallerSensitive
@ForceInline 
public void setLong(Object obj, long l) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

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

Usage

From source file:com.baidu.drapi.autosdk.core.CommonService.java

/**
 * Get current version.//from w  ww . ja  v  a  2  s . c  o m
 * @return
 */
//    protected Version getCurrentVersion() {
//        return currentVersion;
//    }

private void setField(Field field, String value) throws Exception {
    field.setAccessible(true);
    Class<?> cls = field.getType();
    if (cls.equals(int.class)) {
        field.setInt(this, Integer.parseInt(value));
    } else if (cls.equals(long.class)) {
        field.setLong(this, Long.parseLong(value));
    } else if (cls.equals(boolean.class)) {
        field.setBoolean(this, Boolean.parseBoolean(value));
    } else if (cls.equals(Integer.class)) {
        field.set(this, Integer.parseInt(value));
    } else if (cls.equals(Long.class)) {
        field.set(this, Long.parseLong(value));
    } else if (cls.equals(Boolean.class)) {
        field.set(this, Boolean.parseBoolean(value));
    } else {
        field.set(this, value);
    }
}

From source file:com.cloudbees.jenkins.plugins.enterpriseplugins.CloudBeesUpdateSite.java

/**
 * Sets the data timestamp (and tries to propagate the change to {@link UpdateSite#dataTimestamp}
 *
 * @param dataTimestamp the new data timestamp.
 *//* w  ww  .j a  va  2 s.  c o  m*/
private void setDataTimestamp(long dataTimestamp) {
    try {
        // try reflection to be safe for the parent class changing the location
        Field field = UpdateSite.class.getDeclaredField("dataTimestamp");
        boolean accessible = field.isAccessible();
        try {
            field.setLong(this, dataTimestamp);
        } finally {
            if (!accessible) {
                field.setAccessible(false);
            }
        }
    } catch (Throwable e) {
        // ignore
    }
    this.dataTimestamp = dataTimestamp;
}

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

private void configureField(Object check, Field field, String value) {
    try {/*from   ww w . jav  a 2 s . c  om*/
        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: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 2  s  . c om

    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:lineage2.gameserver.Config.java

/**
 * Method setField.//from ww w .  ja v  a  2s  .  com
 * @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.qmetry.qaf.automation.data.BaseDataBean.java

protected void setField(Field field, String val) {
    try {//from   w  ww . ja v  a  2  s  .  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:cn.edu.zafu.corepage.base.BaseActivity.java

/**
 * ???//from   w  w w.  j av a 2  s .  c om
 *
 * @param savedInstanceState Bundle
 */
private void loadActivitySavedData(Bundle savedInstanceState) {
    Field[] fields = this.getClass().getDeclaredFields();
    Field.setAccessible(fields, true);
    Annotation[] ans;
    for (Field f : fields) {
        ans = f.getDeclaredAnnotations();
        for (Annotation an : ans) {
            if (an instanceof SaveWithActivity) {
                try {
                    String fieldName = f.getName();
                    @SuppressWarnings("rawtypes")
                    Class cls = f.getType();
                    if (cls == int.class || cls == Integer.class) {
                        f.setInt(this, savedInstanceState.getInt(fieldName));
                    } else if (String.class.isAssignableFrom(cls)) {
                        f.set(this, savedInstanceState.getString(fieldName));
                    } else if (Serializable.class.isAssignableFrom(cls)) {
                        f.set(this, savedInstanceState.getSerializable(fieldName));
                    } else if (cls == long.class || cls == Long.class) {
                        f.setLong(this, savedInstanceState.getLong(fieldName));
                    } else if (cls == short.class || cls == Short.class) {
                        f.setShort(this, savedInstanceState.getShort(fieldName));
                    } else if (cls == boolean.class || cls == Boolean.class) {
                        f.setBoolean(this, savedInstanceState.getBoolean(fieldName));
                    } else if (cls == byte.class || cls == Byte.class) {
                        f.setByte(this, savedInstanceState.getByte(fieldName));
                    } else if (cls == char.class || cls == Character.class) {
                        f.setChar(this, savedInstanceState.getChar(fieldName));
                    } else if (CharSequence.class.isAssignableFrom(cls)) {
                        f.set(this, savedInstanceState.getCharSequence(fieldName));
                    } else if (cls == float.class || cls == Float.class) {
                        f.setFloat(this, savedInstanceState.getFloat(fieldName));
                    } else if (cls == double.class || cls == Double.class) {
                        f.setDouble(this, savedInstanceState.getDouble(fieldName));
                    } else if (String[].class.isAssignableFrom(cls)) {
                        f.set(this, savedInstanceState.getStringArray(fieldName));
                    } else if (Parcelable.class.isAssignableFrom(cls)) {
                        f.set(this, savedInstanceState.getParcelable(fieldName));
                    } else if (Bundle.class.isAssignableFrom(cls)) {
                        f.set(this, savedInstanceState.getBundle(fieldName));
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

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  2 s  .  com*/
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 a  va 2s  .c om*/

    /*
     * 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);
    }
}

From source file:at.treedb.backup.Import.java

private void adjustFields(DAOiface dao, Class<?> c, Iterator iter) throws Exception {
    ArrayList<Field> list = ClassDependency.getAllFields(c);
    ArrayList<Field> dbKeys = new ArrayList<Field>();
    ArrayList<Field> detached = new ArrayList<Field>();
    // System.out.println("adjust class:" + c.getSimpleName() + ":");
    for (Field f : list) {
        f.setAccessible(true);/*from   w  ww  .j ava2 s . com*/
        if (f.getAnnotation(Detach.class) != null) {
            detached.add(f);
        } else if (f.getAnnotation(DBkey.class) != null) {
            dbKeys.add(f);
        }
    }
    HashMap<Integer, Integer> detachMap = detachIdMap.get(c);
    HashMap<Integer, Integer> historicMap = historicIdMap.get(c);

    while (iter.hasNext()) {
        List<Object> l = iter.next();
        for (Object o : l) {
            Base b = (Base) o;
            for (Field f : dbKeys) {
                f.setAccessible(true);
                Class<?> clazz = f.getAnnotation(DBkey.class).value();
                HashMap<Integer, Integer> idMap;
                Class<?> sel = null;
                // ClassSelector necessary for ID re-mapping?
                if (clazz.equals(ClassSelector.class)) {
                    sel = ((ClassSelector) b).getClass(f);
                    if (sel == null) {
                        continue;
                    }
                    idMap = classIdMap.get(sel);
                } else {
                    idMap = classIdMap.get(clazz);
                }

                if (sel != null && f.getType().equals(Long.TYPE)) {
                    long oldKey = f.getLong(b);
                    if (oldKey > 0) {
                        int id = UIelement.extractHistIdFromComposedId(oldKey);
                        if (idMap.get(id) != null) {
                            long newKey = (oldKey & 0xffffffff00000000L) + idMap.get(id);
                            f.setLong(b, newKey);
                        }
                    }
                } else {
                    int oldKey = f.getInt(b);
                    if (oldKey > 0) {
                        if (c.getName().contains("CIimage")) {
                            System.out.println(f.getName() + ":" + idMap.get(oldKey));
                        }
                        f.setInt(b, idMap.get(oldKey));
                    }
                }
            }
            // re-attach detached binary data
            for (Field f : detached) {
                int index = f.getAnnotation(Detach.class).index();
                String path = Export.createBinaryPath(index, b.getCID(), detachMap.get(b.getDBid()));
                f.set(b, readData(path));

            }
            // set new historic ID

            b.setHistId(historicMap.get(b.getHistId()));

            if (c.equals(CIfile.class)) {
                ciFileHashSet.add(((CIfile) b).getDBfile());
            }

            dao.update(b);
            // re-import DBfile data
            if (c.equals(DBfile.class)) {
                DBfile file = (DBfile) b;
                if (ciFileHashSet.contains(file.getHistId())) {
                    // adapt CIfile virtual path:
                    // /files/ciId/uiElementId/fileName
                    String[] split = file.getPath().split("/");
                    split[2] = "" + classIdMap.get(CI.class).get(Integer.parseInt(split[2]));
                    long composed = Long.parseLong(split[3]);
                    int id = UIelement.extractHistIdFromComposedId(composed);
                    HashMap<Integer, Integer> idMap = classIdMap
                            .get(UIelement.getClassIdFromComposedId(composed));
                    split[3] = "" + ((composed & 0xffffffff00000000L) + idMap.get(id));
                    StringBuffer buf = new StringBuffer();
                    for (String s : split) {
                        if (s.equals("")) {
                            continue;
                        }
                        buf.append("/");
                        buf.append(s);
                    }
                    dBFilePathField.set(file, buf.toString());
                }
                writeFile(dao, file, Export.FILES_DIR + fileIdMap.get(file.getDBid()));
            }
            dao.flush();
            // try to free memory
            if (b instanceof CIblob) {
                // for EclipseLink a session clearing necessary! only
                // detaching isn't working really -
                // memory consumption is increasing in spite of detaching
                // objects!
                if (dao.isJPA() && dao.getJPAimpl() == DAO.JPA_IMPL.ECLIPSELINK) {
                    dao.clear();
                } else {
                    dao.detach(b);
                }
                // clear binary data
                ((CIblob) b).resetBlob();
                b = null;
            }
        }
    }
}