Java Code Examples for java.lang.reflect.Field#setByte()

The following examples show how to use java.lang.reflect.Field#setByte() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: zkdoctor   File: ReflectUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 设置指定类的field值
 *
 * @param clazz 类
 * @param field field
 * @param value 值
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
public static void setField(Class<?> clazz, Field field, Object value)
        throws IllegalArgumentException, IllegalAccessException {
    Class<?> fieldType = field.getType();
    if (int.class.equals(fieldType)) {
        field.setInt(clazz, Integer.parseInt(String.valueOf(value)));
    } else if (boolean.class.equals(fieldType)) {
        field.setBoolean(clazz, Boolean.parseBoolean(String.valueOf(value)));
    } else if (byte.class.equals(fieldType)) {
        field.setByte(clazz, Byte.parseByte(String.valueOf(value)));
    } else if (double.class.equals(fieldType)) {
        field.setDouble(clazz, Double.parseDouble(String.valueOf(value)));
    } else if (float.class.equals(fieldType)) {
        field.setFloat(clazz, Float.parseFloat(String.valueOf(value)));
    } else if (long.class.equals(fieldType)) {
        field.setLong(clazz, Long.parseLong(String.valueOf(value)));
    } else if (short.class.equals(fieldType)) {
        field.setShort(clazz, Short.parseShort(String.valueOf(value)));
    } else if (char.class.equals(fieldType) && value instanceof Character) {
        field.setChar(clazz, (Character) value);
    } else {
        field.set(clazz, value);
    }
}
 
Example 2
Source Project: json-snapshot.github.io   File: SnapshotCaptor.java    License: MIT License 6 votes vote down vote up
public Object removeIgnored(Object value) {
  Object newValue = value;
  if (ignore != null && ignore.length > 0) {
    newValue = shallowCopy(value);
    for (String each : ignore) {
      try {
        Field field = this.argumentClass.getDeclaredField(each);
        field.setAccessible(true);
        if (field.getType().isPrimitive()) {
          field.setByte(newValue, Integer.valueOf(0).byteValue());
        } else {
          field.set(newValue, null);
        }
      } catch (IllegalAccessException | NoSuchFieldException e) {
        throw new SnapshotMatchException("Invalid Ignore value " + each, e.getCause());
      }
    }
  }
  return newValue;
}
 
Example 3
void setVal(Field f, int i) {
    try {
        if (f.getType() == int.class) {
            f.setInt(this, i);
            return;
        } else if (f.getType() == short.class) {
            f.setShort(this, (short)i);
            return;
        } else if (f.getType() == byte.class) {
            f.setByte(this, (byte)i);
            return;
        } else if (f.getType() == long.class) {
            f.setLong(this, i);
            return;
        }
    } catch(IllegalAccessException iae) {
        throw new RuntimeException("Getting fields failed");
    }
    throw new RuntimeException("unexpected field type");
}
 
Example 4
Source Project: android-lite-orm   File: FieldUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void setNumber(Object o, Field field, long n) throws IllegalAccessException {
    field.setAccessible(true);
    Class claxx = field.getType();
    if (claxx == long.class) {
        field.setLong(o, n);
    } else if (claxx == int.class) {
        field.setInt(o, (int) n);
    } else if (claxx == short.class) {
        field.setShort(o, (short) n);
    } else if (claxx == byte.class) {
        field.setByte(o, (byte) n);
    } else if (claxx == Long.class) {
        field.set(o, new Long(n));
    } else if (claxx == Integer.class) {
        field.set(o, new Integer((int) n));
    } else if (claxx == Short.class) {
        field.set(o, new Short((short) n));
    } else if (claxx == Byte.class) {
        field.set(o, new Byte((byte) n));
    } else {
        throw new RuntimeException("field is not a number class");
    }
}
 
Example 5
Source Project: radon   File: StaticSet.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void handle(VM vm, Object[] operands) throws Exception {
    String ownerName = (String) operands[0];
    String name = (String) operands[1];
    String typeName = (String) operands[2];

    Class clazz = VM.getClazz(ownerName);
    Class type = VM.getClazz(typeName);
    Field field = VM.getField(clazz, name, type);

    if (field == null)
        throw new VMException();

    JWrapper value = vm.pop();

    if (value instanceof JTop)
        value = vm.pop();

    if ("int".equals(ownerName))
        field.setInt(null, value.asInt());
    else if ("long".equals(ownerName))
        field.setLong(null, value.asLong());
    else if ("float".equals(ownerName))
        field.setFloat(null, value.asFloat());
    else if ("double".equals(ownerName))
        field.setDouble(null, value.asDouble());
    else if ("byte".equals(ownerName))
        field.setByte(null, value.asByte());
    else if ("short".equals(ownerName))
        field.setShort(null, value.asShort());
    else if ("char".equals(ownerName))
        field.setChar(null, value.asChar());
    else if ("boolean".equals(ownerName))
        field.setBoolean(null, value.asBool());
    else
        field.set(null, value.asObj());
}
 
Example 6
Source Project: radon   File: VirtSet.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void handle(VM vm, Object[] operands) throws Exception {
    String ownerName = (String) operands[0];
    String name = (String) operands[1];
    String typeName = (String) operands[2];

    Class clazz = VM.getClazz(ownerName);
    Class type = VM.getClazz(typeName);
    Field field = VM.getField(clazz, name, type);

    if (field == null)
        throw new VMException();

    JWrapper value = vm.pop();

    if (value instanceof JTop)
        value = vm.pop();

    Object ref = vm.pop().asObj();

    if ("int".equals(ownerName))
        field.setInt(ref, value.asInt());
    else if ("long".equals(ownerName))
        field.setLong(ref, value.asLong());
    else if ("float".equals(ownerName))
        field.setFloat(ref, value.asFloat());
    else if ("double".equals(ownerName))
        field.setDouble(ref, value.asDouble());
    else if ("byte".equals(ownerName))
        field.setByte(ref, value.asByte());
    else if ("short".equals(ownerName))
        field.setShort(ref, value.asShort());
    else if ("char".equals(ownerName))
        field.setChar(ref, value.asChar());
    else if ("boolean".equals(ownerName))
        field.setBoolean(ref, value.asBool());
    else
        field.set(ref, value.asObj());
}
 
Example 7
/**
 * Sets a field from a string. It only supports fields where {@link
 * ConfigCommandUtils#isSupportedType(Class)} for {@link Field#getType()}
 *
 * @param string The string to set the field's value to
 * @param field  The field to set
 * @param object The object upon which to set the field
 */
public static void setFieldFromString(String string, Field field, @Nullable Object object) {
    if (!isSupportedType(field.getType())) {
        throw new IllegalArgumentException("Unsupported field type");
    }
    try {
        if (field.getType() == int.class) {
            field.setInt(object, Integer.parseInt(string));
        } else if (field.getType() == double.class) {
            field.setDouble(object, Double.parseDouble(string));
        } else if (field.getType() == float.class) {
            field.setFloat(object, Float.parseFloat(string));
        } else if (field.getType() == boolean.class) {
            field.setBoolean(object, Boolean.parseBoolean(string));
        } else if (field.getType() == byte.class) {
            field.setByte(object, Byte.parseByte(string));
        } else if (field.getType() == long.class) {
            field.setLong(object, Long.parseLong(string));
        } else if (field.getType() == short.class) {
            field.setShort(object, Short.parseShort(string));
        } else if (field.getType() == char.class) {
            field.setChar(object, string.charAt(0));
        } else if (field.getType() == String.class) {
            field.set(object, string);
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 8
Source Project: ParcelableGenerator   File: PGUtils.java    License: MIT License 5 votes vote down vote up
private static void readValue(Parcel source, Field field, Object target) {
    try {
        if (!checkSerializable(field)) {
            return;
        }
        field.setAccessible(true);
        if (field.getType().equals(int.class)) {
            field.setInt(target, source.readInt());
        } else if (field.getType().equals(double.class)) {
            field.setDouble(target, source.readDouble());
        } else if (field.getType().equals(float.class)) {
            field.setFloat(target, source.readFloat());
        } else if (field.getType().equals(long.class)) {
            field.setLong(target, source.readLong());
        } else if (field.getType().equals(boolean.class)) {
            field.setBoolean(target, source.readInt() != 0);
        } else if (field.getType().equals(char.class)) {
            field.setChar(target, (char) source.readInt());
        } else if (field.getType().equals(byte.class)) {
            field.setByte(target, source.readByte());
        } else if (field.getType().equals(short.class)) {
            field.setShort(target, (short) source.readInt());
        } else {
            field.set(target,
                    source.readValue(target.getClass().getClassLoader()));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 9
Source Project: pacaya   File: ArgParser.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private static void setField(Object obj, Field field, String value) throws IllegalArgumentException,
        IllegalAccessException {
    Class<?> type = field.getType();
    if (type.equals(Boolean.TYPE)) {
        field.setBoolean(obj, Boolean.parseBoolean(value));
    } else if (type.equals(Byte.TYPE)) {
        field.setByte(obj, Byte.parseByte(value));
    } else if (type.equals(Character.TYPE)) {
        field.setChar(obj, parseChar(value));
    } else if (type.equals(Double.TYPE)) {
        field.setDouble(obj, Double.parseDouble(value));
    } else if (type.equals(Float.TYPE)) {
        field.setFloat(obj, Float.parseFloat(value));
    } else if (type.equals(Integer.TYPE)) {
        field.setInt(obj, safeStrToInt(value));
    } else if (type.equals(Long.TYPE)) {
        field.setLong(obj, Long.parseLong(value));
    } else if (type.equals(Short.TYPE)) {
        field.setShort(obj, Short.parseShort(value));
    } else if (type.isEnum()) {
        field.set(obj, Enum.valueOf((Class<Enum>) field.getType(), value));
    } else if (type.equals(String.class)) {
        field.set(obj, value);
    } else if (type.equals(File.class)) {
        field.set(obj, new File(value));
    } else if (type.equals(Date.class)) {
        DateFormat df = new SimpleDateFormat("MM-dd-yy.hh:mma");
        try {
            field.set(obj, df.parse(value));
        } catch (java.text.ParseException e) {
            throw new RuntimeException(e);
        }
    } else {
        throw new RuntimeException("Field type not supported: " + type.getName());
    }
}
 
Example 10
Source Project: azeroth   File: ExcelReader.java    License: Apache License 2.0 4 votes vote down vote up
private void getCellValue(Cell cell, Object o, Field field) throws IllegalAccessException, ParseException {
    LOG.debug("cell:{}, field:{}, type:{}", cell.getCellTypeEnum(), field.getName(), field.getType().getName());
    switch (cell.getCellTypeEnum()) {
        case BLANK:
            break;
        case BOOLEAN:
            field.setBoolean(o, cell.getBooleanCellValue());
            break;
        case ERROR:
            field.setByte(o, cell.getErrorCellValue());
            break;
        case FORMULA:
            field.set(o, cell.getCellFormula());
            break;
        case NUMERIC:
            if (DateUtil.isCellDateFormatted(cell)) {
                if (field.getType().getName().equals(Date.class.getName())) {
                    field.set(o, cell.getDateCellValue());
                } else {
                    field.set(o, format.format(cell.getDateCellValue()));
                }
            } else {
                if (field.getType().isAssignableFrom(Integer.class) || field.getType().getName().equals("int")) {
                    field.setInt(o, (int) cell.getNumericCellValue());
                } else if (field.getType().isAssignableFrom(Short.class) || field.getType().getName().equals("short")) {
                    field.setShort(o, (short) cell.getNumericCellValue());
                } else if (field.getType().isAssignableFrom(Float.class) || field.getType().getName().equals("float")) {
                    field.setFloat(o, (float) cell.getNumericCellValue());
                } else if (field.getType().isAssignableFrom(Byte.class) || field.getType().getName().equals("byte")) {
                    field.setByte(o, (byte) cell.getNumericCellValue());
                } else if (field.getType().isAssignableFrom(Double.class) || field.getType().getName().equals("double")) {
                    field.setDouble(o, cell.getNumericCellValue());
                } else if (field.getType().isAssignableFrom(String.class)) {
                    String s = String.valueOf(cell.getNumericCellValue());
                    if (s.contains("E")) {
                        s = s.trim();
                        BigDecimal bigDecimal = new BigDecimal(s);
                        s = bigDecimal.toPlainString();
                    }
                    //防止整数判定为浮点数
                    if (s.endsWith(".0")) { s = s.substring(0, s.indexOf(".0")); }
                    field.set(o, s);
                } else {
                    field.set(o, cell.getNumericCellValue());
                }
            }
            break;
        case STRING:
            if (field.getType().getName().equals(Date.class.getName())) {
                field.set(o, format.parse(cell.getRichStringCellValue().getString()));
            } else {
                field.set(o, cell.getRichStringCellValue().getString());
            }
            break;
        default:
            field.set(o, cell.getStringCellValue());
            break;
    }
}
 
Example 11
Source Project: jeesuite-libs   File: ExcelReader.java    License: Apache License 2.0 4 votes vote down vote up
private void getCellValue(Cell cell, Object o, Field field) throws IllegalAccessException, ParseException {
    LOG.debug("cell:{}, field:{}, type:{}", cell.getCellTypeEnum(), field.getName(), field.getType().getName());
    switch (cell.getCellTypeEnum()) {
        case BLANK:
            break;
        case BOOLEAN:
            field.setBoolean(o, cell.getBooleanCellValue());
            break;
        case ERROR:
            field.setByte(o, cell.getErrorCellValue());
            break;
        case FORMULA:
            field.set(o, cell.getCellFormula());
            break;
        case NUMERIC:
            if (DateUtil.isCellDateFormatted(cell)) {
                if (field.getType().getName().equals(Date.class.getName())) {
                    field.set(o, cell.getDateCellValue());
                } else {
                    field.set(o, format.format(cell.getDateCellValue()));
                }
            } else {
                if (field.getType().isAssignableFrom(Integer.class) || field.getType().getName().equals("int")) {
                    field.setInt(o, (int) cell.getNumericCellValue());
                } else if (field.getType().isAssignableFrom(Short.class) || field.getType().getName().equals("short")) {
                    field.setShort(o, (short) cell.getNumericCellValue());
                } else if (field.getType().isAssignableFrom(Float.class) || field.getType().getName().equals("float")) {
                    field.setFloat(o, (float) cell.getNumericCellValue());
                } else if (field.getType().isAssignableFrom(Byte.class) || field.getType().getName().equals("byte")) {
                    field.setByte(o, (byte) cell.getNumericCellValue());
                } else if (field.getType().isAssignableFrom(Double.class) || field.getType().getName().equals("double")) {
                    field.setDouble(o, cell.getNumericCellValue());
                } else if (field.getType().isAssignableFrom(String.class)) {
                    String s = String.valueOf(cell.getNumericCellValue());
                    if (s.contains("E")) {
                        s = s.trim();
                        BigDecimal bigDecimal = new BigDecimal(s);
                        s = bigDecimal.toPlainString();
                    }
                    //防止整数判定为浮点数
                    if (s.endsWith(".0"))
                        s = s.substring(0, s.indexOf(".0"));
                    field.set(o, s);
                } else {
                    field.set(o, cell.getNumericCellValue());
                }
            }
            break;
        case STRING:
            if (field.getType().getName().equals(Date.class.getName())) {
                field.set(o, format.parse(cell.getRichStringCellValue().getString()));
            } else {
                field.set(o, cell.getRichStringCellValue().getString());
            }
            break;
        default:
            field.set(o, cell.getStringCellValue());
            break;
    }
}
 
Example 12
Source Project: j2objc   File: FieldTest.java    License: Apache License 2.0 4 votes vote down vote up
void setField(char primitiveType, Object o, Field f,
        Class expected, Object value) {
    try {
        primitiveType = Character.toUpperCase(primitiveType);
        switch (primitiveType) {
        case 'I': // int
            f.setInt(o, ((Integer) value).intValue());
            break;
        case 'J': // long
            f.setLong(o, ((Long) value).longValue());
            break;
        case 'Z': // boolean
            f.setBoolean(o, ((Boolean) value).booleanValue());
            break;
        case 'S': // short
            f.setShort(o, ((Short) value).shortValue());
            break;
        case 'B': // byte
            f.setByte(o, ((Byte) value).byteValue());
            break;
        case 'C': // char
            f.setChar(o, ((Character) value).charValue());
            break;
        case 'D': // double
            f.setDouble(o, ((Double) value).doubleValue());
            break;
        case 'F': // float
            f.setFloat(o, ((Float) value).floatValue());
            break;
        default:
            f.set(o, value);
        }
        // Since 2011, members are always accessible and throwing is optional
        assertTrue("expected " + expected + " for " + f.getName() + " = " + value,
                expected == null || expected == IllegalAccessException.class);
    } catch (Exception e) {
        if (expected == null) {
            e.printStackTrace();
            fail("unexpected exception " + e + " for field "
                    + f.getName() + ", value " + value);
        } else {
            assertTrue("expected exception "
                    + expected.getName() + " and got " + e
                    + " for field " + f.getName() + ", value " + value,
                    e.getClass().equals(expected));
        }
    }
}
 
Example 13
private static void setInstanceValue(@NonNull Field field, @NonNull Object obj,
        @NonNull Bundle bundle, @NonNull String key, boolean isGson)
        throws IllegalArgumentException, IllegalAccessException {

    if (isGson) {
        field.set(obj, GsonHelper.fromJson(bundle.getString(key), field.getGenericType()));
        return;
    }

    Class<?> type = field.getType();

    Type[] genericTypes = null;
    if (field.getGenericType() instanceof ParameterizedType) {
        genericTypes = ((ParameterizedType) field.getGenericType()).getActualTypeArguments();
    }

    if (type.equals(Boolean.TYPE)) {
        field.setBoolean(obj, bundle.getBoolean(key));

    } else if (type.equals(boolean[].class)) {
        field.set(obj, bundle.getBooleanArray(key));

    } else if (type.equals(Bundle.class)) {
        field.set(obj, bundle.getBundle(key));

    } else if (type.equals(Byte.TYPE)) {
        field.setByte(obj, bundle.getByte(key));

    } else if (type.equals(byte[].class)) {
        field.set(obj, bundle.getByteArray(key));

    } else if (type.equals(Character.TYPE)) {
        field.setChar(obj, bundle.getChar(key));

    } else if (type.equals(char[].class)) {
        field.set(obj, bundle.getCharArray(key));

    } else if (type.equals(CharSequence.class)) {
        field.set(obj, bundle.getCharSequence(key));

    } else if (type.equals(CharSequence[].class)) {
        field.set(obj, bundle.getCharSequenceArray(key));

    } else if (type.equals(Double.TYPE)) {
        field.setDouble(obj, bundle.getDouble(key));

    } else if (type.equals(double[].class)) {
        field.set(obj, bundle.getDoubleArray(key));

    } else if (type.equals(Float.TYPE)) {
        field.setFloat(obj, bundle.getFloat(key));

    } else if (type.equals(float[].class)) {
        field.set(obj, bundle.getFloatArray(key));

    } else if (type.equals(Integer.TYPE)) {
        field.setInt(obj, bundle.getInt(key));

    } else if (type.equals(int[].class)) {
        field.set(obj, bundle.getIntArray(key));

    } else if (type.equals(Long.TYPE)) {
        field.setLong(obj, bundle.getLong(key));

    } else if (type.equals(long[].class)) {
        field.set(obj, bundle.getLongArray(key));

    } else if (type.equals(Short.TYPE)) {
        field.setShort(obj, bundle.getShort(key));

    } else if (type.equals(short[].class)) {
        field.set(obj, bundle.getShortArray(key));

    } else if (type.equals(String.class)) {
        field.set(obj, bundle.getString(key));

    } else if (type.equals(String[].class)) {
        field.set(obj, bundle.getStringArray(key));

    } else if (Parcelable.class.isAssignableFrom(type)) {
        field.set(obj, bundle.getParcelable(key));

    } else if (type.equals(ArrayList.class)
            && genericTypes != null
            && genericTypes[0] instanceof Class
            && Parcelable.class.isAssignableFrom((Class<?>) genericTypes[0])) {
        field.set(obj, bundle.getParcelableArrayList(key));

    } else if (type.isArray() && Parcelable.class.isAssignableFrom(type.getComponentType())) {
        field.set(obj, bundle.getParcelableArray(key));

    } else if (Serializable.class.isAssignableFrom(type)) {
        field.set(obj, bundle.getSerializable(key));

    } else {
        throw new RuntimeException("Unsupported field type: " + field.getName()
                + ", " + type.getSimpleName());
    }

    bundle.remove(key);
}