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:MyClass.java

public static void main(String[] args) throws Exception {
    Class<?> clazz = Class.forName("MyClass");
    MyClass x = (MyClass) clazz.newInstance();

    Field f = clazz.getField("i");
    System.out.println(f.getLong(x));

    f.setLong(x, 9L);
    System.out.println(f.getLong(x));

}

From source file:Tweedle.java

public static void main(String... args) {
    Book book = new Book();
    String fmt = "%6S:  %-12s = %s%n";

    try {//from   w ww  .  ja va  2s . com
        Class<?> c = book.getClass();

        Field chap = c.getDeclaredField("chapters");
        out.format(fmt, "before", "chapters", book.chapters);
        chap.setLong(book, 12);
        out.format(fmt, "after", "chapters", chap.getLong(book));

        Field chars = c.getDeclaredField("characters");
        out.format(fmt, "before", "characters", Arrays.asList(book.characters));
        String[] newChars = { "Queen", "King" };
        chars.set(book, newChars);
        out.format(fmt, "after", "characters", Arrays.asList(book.characters));

        Field t = c.getDeclaredField("twin");
        out.format(fmt, "before", "twin", book.twin);
        t.set(book, Tweedle.DUM);
        out.format(fmt, "after", "twin", t.get(book));

        // production code should handle these exceptions more gracefully
    } catch (NoSuchFieldException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    }
}

From source file:Main.java

public static void keep_setLong(Field field, Object obj, Cursor cursor, int i) {
    try {//from www. ja v a 2  s  .  com
        if (field.getType().equals(Long.TYPE))
            field.setLong(obj, cursor.getLong(i));
        else
            field.set(obj, Long.valueOf(cursor.getLong(i)));
    } catch (Exception exception) {
        exception.printStackTrace();
    }
}

From source file:org.apache.lens.ml.AlgoArgParser.java

/**
 * Extracts feature names. If the algo has any parameters associated with @AlgoParam annotation, those are set
 * as well.//from  w  w w .java  2  s.  com
 *
 * @param algo the algo
 * @param args    the args
 * @return List of feature column names.
 */
public static List<String> parseArgs(MLAlgo algo, String[] args) {
    List<String> featureColumns = new ArrayList<String>();
    Class<? extends MLAlgo> algoClass = algo.getClass();
    // Get param fields
    Map<String, Field> fieldMap = new HashMap<String, Field>();

    for (Field fld : algoClass.getDeclaredFields()) {
        fld.setAccessible(true);
        AlgoParam paramAnnotation = fld.getAnnotation(AlgoParam.class);
        if (paramAnnotation != null) {
            fieldMap.put(paramAnnotation.name(), fld);
        }
    }

    for (int i = 0; i < args.length; i += 2) {
        String key = args[i].trim();
        String value = args[i + 1].trim();

        try {
            if ("feature".equalsIgnoreCase(key)) {
                featureColumns.add(value);
            } else if (fieldMap.containsKey(key)) {
                Field f = fieldMap.get(key);
                if (String.class.equals(f.getType())) {
                    f.set(algo, value);
                } else if (Integer.TYPE.equals(f.getType())) {
                    f.setInt(algo, Integer.parseInt(value));
                } else if (Double.TYPE.equals(f.getType())) {
                    f.setDouble(algo, Double.parseDouble(value));
                } else if (Long.TYPE.equals(f.getType())) {
                    f.setLong(algo, Long.parseLong(value));
                } else {
                    // check if the algo provides a deserializer for this param
                    String customParserClass = algo.getConf().getProperties().get("lens.ml.args." + key);
                    if (customParserClass != null) {
                        Class<? extends CustomArgParser<?>> clz = (Class<? extends CustomArgParser<?>>) Class
                                .forName(customParserClass);
                        CustomArgParser<?> parser = clz.newInstance();
                        f.set(algo, parser.parse(value));
                    } else {
                        LOG.warn("Ignored param " + key + "=" + value + " as no parser found");
                    }
                }
            }
        } catch (Exception exc) {
            LOG.error("Error while setting param " + key + " to " + value + " for algo " + algo);
        }
    }
    return featureColumns;
}

From source file:org.apache.lens.ml.TrainerArgParser.java

/**
 * Extracts feature names. If the trainer has any parameters associated with @TrainerParam annotation, those are set
 * as well.//w ww  .j  a  v  a 2  s . c  o m
 *
 * @param trainer
 *          the trainer
 * @param args
 *          the args
 * @return List of feature column names.
 */
public static List<String> parseArgs(MLTrainer trainer, String[] args) {
    List<String> featureColumns = new ArrayList<String>();
    Class<? extends MLTrainer> trainerClass = trainer.getClass();
    // Get param fields
    Map<String, Field> fieldMap = new HashMap<String, Field>();

    for (Field fld : trainerClass.getDeclaredFields()) {
        fld.setAccessible(true);
        TrainerParam paramAnnotation = fld.getAnnotation(TrainerParam.class);
        if (paramAnnotation != null) {
            fieldMap.put(paramAnnotation.name(), fld);
        }
    }

    for (int i = 0; i < args.length; i += 2) {
        String key = args[i].trim();
        String value = args[i + 1].trim();

        try {
            if ("feature".equalsIgnoreCase(key)) {
                featureColumns.add(value);
            } else if (fieldMap.containsKey(key)) {
                Field f = fieldMap.get(key);
                if (String.class.equals(f.getType())) {
                    f.set(trainer, value);
                } else if (Integer.TYPE.equals(f.getType())) {
                    f.setInt(trainer, Integer.parseInt(value));
                } else if (Double.TYPE.equals(f.getType())) {
                    f.setDouble(trainer, Double.parseDouble(value));
                } else if (Long.TYPE.equals(f.getType())) {
                    f.setLong(trainer, Long.parseLong(value));
                } else {
                    // check if the trainer provides a deserializer for this param
                    String customParserClass = trainer.getConf().getProperties().get("lens.ml.args." + key);
                    if (customParserClass != null) {
                        Class<? extends CustomArgParser<?>> clz = (Class<? extends CustomArgParser<?>>) Class
                                .forName(customParserClass);
                        CustomArgParser<?> parser = clz.newInstance();
                        f.set(trainer, parser.parse(value));
                    } else {
                        LOG.warn("Ignored param " + key + "=" + value + " as no parser found");
                    }
                }
            }
        } catch (Exception exc) {
            LOG.error("Error while setting param " + key + " to " + value + " for trainer " + trainer);
        }
    }
    return featureColumns;
}

From source file:com.browseengine.bobo.serialize.JSONSerializer.java

private static void loadObject(Object retObj, Field f, JSONObject jsonObj) throws JSONSerializationException {
    String key = f.getName();/* ww w. ja  va  2s  . c o  m*/
    Class type = f.getType();
    try {
        if (type.isPrimitive()) {
            if (type == Integer.TYPE) {
                f.setInt(retObj, jsonObj.getInt(key));
            } else if (type == Long.TYPE) {
                f.setLong(retObj, jsonObj.getInt(key));
            } else if (type == Short.TYPE) {
                f.setShort(retObj, (short) jsonObj.getInt(key));
            } else if (type == Boolean.TYPE) {
                f.setBoolean(retObj, jsonObj.getBoolean(key));
            } else if (type == Double.TYPE) {
                f.setDouble(retObj, jsonObj.getDouble(key));
            } else if (type == Float.TYPE) {
                f.setFloat(retObj, (float) jsonObj.getDouble(key));
            } else if (type == Character.TYPE) {
                char ch = jsonObj.getString(key).charAt(0);
                f.setChar(retObj, ch);
            } else if (type == Byte.TYPE) {
                f.setByte(retObj, (byte) jsonObj.getInt(key));
            } else {
                throw new JSONSerializationException("Unknown primitive: " + type);
            }
        } else if (type == String.class) {
            f.set(retObj, jsonObj.getString(key));
        } else if (JSONSerializable.class.isAssignableFrom(type)) {
            JSONObject jObj = jsonObj.getJSONObject(key);
            JSONSerializable serObj = deSerialize(type, jObj);
            f.set(retObj, serObj);
        }
    } catch (Exception e) {
        throw new JSONSerializationException(e.getMessage(), e);
    }
}

From source file:org.sonar.api.batch.rule.Checks.java

private static void configureField(Object check, Field field, String value) {
    try {//from  ww w  .j a v  a 2 s  . com
        field.setAccessible(true);

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

        } else if (int.class == field.getType()) {
            field.setInt(check, Integer.parseInt(value));

        } else if (short.class == field.getType()) {
            field.setShort(check, Short.parseShort(value));

        } else if (long.class == field.getType()) {
            field.setLong(check, Long.parseLong(value));

        } else if (double.class == field.getType()) {
            field.setDouble(check, Double.parseDouble(value));

        } else if (boolean.class == field.getType()) {
            field.setBoolean(check, Boolean.parseBoolean(value));

        } else if (byte.class == field.getType()) {
            field.setByte(check, Byte.parseByte(value));

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

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

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

        } else if (Boolean.class == field.getType()) {
            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.plugins.openedge.foundation.OpenEdgeComponents.java

private static void configureField(Object check, Field field, String value) {
    try {//from  w w w .  j a v a  2 s  . c  o m
        field.setAccessible(true);

        if (field.getType().equals(String.class)) {
            field.set(check, value);
        } else if (int.class == field.getType()) {
            field.setInt(check, Integer.parseInt(value));
        } else if (short.class == field.getType()) {
            field.setShort(check, Short.parseShort(value));
        } else if (long.class == field.getType()) {
            field.setLong(check, Long.parseLong(value));
        } else if (double.class == field.getType()) {
            field.setDouble(check, Double.parseDouble(value));
        } else if (boolean.class == field.getType()) {
            field.setBoolean(check, Boolean.parseBoolean(value));
        } else if (byte.class == field.getType()) {
            field.setByte(check, Byte.parseByte(value));
        } else if (Integer.class == field.getType()) {
            field.set(check, new Integer(Integer.parseInt(value)));
        } else if (Long.class == field.getType()) {
            field.set(check, new Long(Long.parseLong(value)));
        } else if (Double.class == field.getType()) {
            field.set(check, new Double(Double.parseDouble(value)));
        } else if (Boolean.class == field.getType()) {
            field.set(check, Boolean.valueOf(Boolean.parseBoolean(value)));
        } else {
            throw MessageException
                    .of("The type of the field " + field + " is not supported: " + field.getType());
        }
    } catch (IllegalAccessException e) {
        throw MessageException.of(
                "Can not set the value of the field " + field + " in the class: " + check.getClass().getName(),
                e);
    }
}

From source file:com.vk.sdk.api.model.ParseUtils.java

/**
* Parses object with follow rules://from   ww w  .  j a v  a2 s .co m
*
* 1. All fields should had a public access.
* 2. The name of the filed should be fully equal to name of JSONObject key.
* 3. Supports parse of all Java primitives, all {@link String},
* arrays of primitive types, {@link String}s and {@link com.vk.sdk.api.model.VKApiModel}s,
* list implementation line {@link com.vk.sdk.api.model.VKList}, {@link com.vk.sdk.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdk.api.model.VKPhotoSizes},
* {@link com.vk.sdk.api.model.VKApiModel}s.
*
* 4. Boolean fields defines by vk_int == 1 expression.
* @param object object to initialize
* @param source data to read values
* @return initialized according with given data object
* @throws JSONException if source object structure is invalid
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Parcelable.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            // ?????????? ???????:
            // ?? ?? ????????, ?? ? ????????? ???????? getFields() ???????? ??? ???.
            // ?????? ? ??????? ???????????, ????????? ?? ? ????????, ?????? Android ? ???????? ????????? ??????????.
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:org.flycraft.vkontakteapi.model.ParseUtils.java

/**
 * Parses object with follow rules://  w  w w  .  ja  v  a2  s.c o m
 * <p/>
 * 1. All fields should had a public access.
 * 2. The name of the filed should be fully equal to name of JSONObject key.
 * 3. Supports parse of all Java primitives, all {@link java.lang.String},
 * arrays of primitive types, {@link java.lang.String}s and {@link org.flycraft.vkontakteapi.model.VKApiModel}s,
 * list implementation line {@link org.flycraft.vkontakteapi.model.VKList}, {@link org.flycraft.vkontakteapi.model.VKAttachments.VKApiAttachment} or {@link org.flycraft.vkontakteapi.model.VKPhotoSizes},
 * {@link org.flycraft.vkontakteapi.model.VKApiModel}s.
 * <p/>
 * 4. Boolean fields defines by vk_int == 1 expression.
 *
 * @param object object to initialize
 * @param source data to read values
 * @param <T>    type of result
 * @return initialized according with given data object
 * @throws JSONException if source object structure is invalid
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            //  ?:
            //   ,     getFields()   .
            //  ? ? ?,   ? ?,  Android  ?  .
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}