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

The following examples show how to use java.lang.reflect.Field#setFloat() . 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 File: ReflectUtils.java    From zkdoctor with 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 File: ConfigCommandUtils.java    From Valkyrien-Skies with Apache License 2.0 5 votes vote down vote up
/**
 * 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 3
Source File: Arguments.java    From h2o-2 with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts bindings and options; and sets appropriate fields in the
 * CommandLineArgument object.
 */
private int extract(Arg arg, Field[] fields) {
  int count = 0;
  for( Field field : fields ){
    String name = field.getName();
    Class cl = field.getType();
    String opt = getValue(name); // optional value
    try{
      if( cl.isPrimitive() ){
        if( cl == Boolean.TYPE ){
          boolean curval = field.getBoolean(arg);
          boolean xval = curval;
          if( opt != null ) xval = !curval;
          if( "1".equals(opt) || "true" .equals(opt) ) xval = true;
          if( "0".equals(opt) || "false".equals(opt) ) xval = false;
          if( opt != null ) field.setBoolean(arg, xval);
        }else if( opt == null || opt.length()==0 ) continue;
        else if( cl == Integer.TYPE ) field.setInt(arg, Integer.parseInt(opt));
        else if( cl == Float.TYPE ) field.setFloat(arg, Float.parseFloat(opt));
        else if( cl == Double.TYPE ) field.setDouble(arg, Double.parseDouble(opt));
        else if( cl == Long.TYPE ) field.setLong(arg, Long.parseLong(opt));
        else continue;
        count++;
      }else if( cl == String.class ){
        if( opt != null ){
          field.set(arg, opt);
          count++;
        }
      }
    } catch( Exception e ) { Log.err("Argument failed with ",e); }
  }
  Arrays.sort(commandLineArgs);
  for( int i = 0; i < commandLineArgs.length; i++ )
    commandLineArgs[i].position = i;
  return count;
}
 
Example 4
Source File: ArgParser.java    From pacaya with 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 5
Source File: CmdLineParser.java    From mltk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Parses the command line arguments.
 * 
 * @param args the command line arguments.
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
public void parse(String[] args) throws IllegalArgumentException, IllegalAccessException {
	if (args.length % 2 != 0) {
		throw new IllegalArgumentException();
	}
	Map<String, String> map = new HashMap<>();
	for (int i = 0; i < args.length; i += 2) {
		map.put(args[i], args[i + 1]);
	}
	for (int i = 0; i < argList.size(); i++) {
		Field field = fieldList.get(i);
		Argument arg = argList.get(i);
		String value = map.get(arg.name());
		if (value != null) {
			Class<? extends Object> fclass = field.getType();
			field.setAccessible(true);
			if (fclass == String.class) {
				field.set(obj, value);
			} else if (fclass == int.class) {
				field.setInt(obj, Integer.parseInt(value));
			} else if (fclass == double.class) {
				field.setDouble(obj, Double.parseDouble(value));
			} else if (fclass == float.class) {
				field.setFloat(obj, Float.parseFloat(value));
			} else if (fclass == boolean.class) {
				field.setBoolean(obj, Boolean.parseBoolean(value));
			} else if (fclass == long.class) {
				field.setLong(obj, Long.parseLong(value));
			} else if (fclass == char.class) {
				field.setChar(obj, value.charAt(0));
			}
		} else if (arg.required()) {
			throw new IllegalArgumentException();
		}
	}
}
 
Example 6
Source File: PGUtils.java    From ParcelableGenerator with 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 7
Source File: HealthBarRenderPowerPatch.java    From StSLib with MIT License 5 votes vote down vote up
public static void Postfix(AbstractCreature __instance, SpriteBatch sb, float x, float y)
{
    try {
        Field f = AbstractCreature.class.getDeclaredField("targetHealthBarWidth");
        f.setAccessible(true);

        float targetHealthBarWidth = f.getFloat(__instance);
        targetHealthBarWidth += nonPoisonWidthSum;
        nonPoisonWidthSum = 0;
        f.setFloat(__instance, targetHealthBarWidth);
    } catch (IllegalAccessException | NoSuchFieldException e) {
        e.printStackTrace();
    }
}
 
Example 8
Source File: JsonBean.java    From AndroidWear-OpenWear with MIT License 5 votes vote down vote up
public void fromJsonObj(JSONObject jsonObj) {
    Field[] fields = getClass().getFields();

    for (Field field : fields) {
        try {
            field.setAccessible(true);

            // 跳过静态成员变量
            boolean isStatic = Modifier.isStatic(field.getModifiers());
            if (isStatic) {
                continue;
            }

            String className = field.getType().getName();
            if (className.equals(String.class.getName())) {
                field.set(this, jsonObj.optString(field.getName()));
            } else if (className.equals(Integer.class.getName()) || className.equals("int")) {
                field.setInt(this, jsonObj.optInt(field.getName()));
            } else if (className.equals(Long.class.getName()) || className.equals("long")) {
                field.setLong(this, jsonObj.optLong(field.getName()));
            } else if (className.equals(Double.class.getName()) || className.equals("double")) {
                field.setDouble(this, jsonObj.optDouble(field.getName(), 0.0d));
            } else if (className.equals(Float.class.getName()) || className.equals("float")) {
                field.setFloat(this, (float) jsonObj.optDouble(field.getName(), 0.0f));
            } else if (className.equals(Boolean.class.getName()) || className.equals("boolean")) {
                field.setBoolean(this, jsonObj.optBoolean(field.getName()));
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
 
Example 9
Source File: DBObject.java    From GLEXP-Team-onebillion with Apache License 2.0 5 votes vote down vote up
private void setFloatField(String name, float value)
{
    try {
        Field field = this.getClass().getDeclaredField(name);
        field.setFloat(this, value);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example 10
Source File: VirtSet.java    From radon with 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 11
Source File: StaticSet.java    From radon with 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 12
Source File: TimerHack.java    From ForgeWurst with GNU General Public License v3.0 5 votes vote down vote up
private void setTickLength(float tickLength)
{
	try
	{
		Field fTimer = mc.getClass().getDeclaredField(
			wurst.isObfuscated() ? "field_71428_T" : "timer");
		fTimer.setAccessible(true);
		
		if(WMinecraft.VERSION.equals("1.10.2"))
		{
			Field fTimerSpeed = Timer.class.getDeclaredField(
				wurst.isObfuscated() ? "field_74278_d" : "timerSpeed");
			fTimerSpeed.setAccessible(true);
			fTimerSpeed.setFloat(fTimer.get(mc), 50 / tickLength);
			
		}else
		{
			Field fTickLength = Timer.class.getDeclaredField(
				wurst.isObfuscated() ? "field_194149_e" : "tickLength");
			fTickLength.setAccessible(true);
			fTickLength.setFloat(fTimer.get(mc), tickLength);
		}
		
	}catch(ReflectiveOperationException e)
	{
		throw new RuntimeException(e);
	}
}
 
Example 13
Source File: SqlHelper.java    From Collection-Android with MIT License 5 votes vote down vote up
/**
 * use reflection to parse queryResult's value into model
 * @param queryResult
 * @param model
 */
public static void parseResultSetToModel(ResultSet queryResult, Object model) {
    Class clazz = model.getClass();
    Field[] fields = clazz.getDeclaredFields();

    Class fieldType;
    try {
        for (Field field:fields) {

            if(field.getName().contains("$")){
                continue;
            }

            if (!field.isAccessible())
                field.setAccessible(true);
            fieldType = field.getType();
            if (fieldType == short.class ||fieldType == Short.class || fieldType == Integer.class||fieldType ==int.class) {
                field.set(model, queryResult.getIntValue(field.getName()));
            } else if (fieldType == Long.class || fieldType == long.class) {
                field.setLong(model,queryResult.getLongValue(field.getName()));
            } else if (fieldType == float.class || fieldType == Float.class) {
                field.setFloat(model,queryResult.getFloatValue(field.getName()));
            } else if (fieldType == Double.class|| fieldType == double.class ) {
                field.setDouble(model,queryResult.getDoubleValue(field.getName()));
            } else if (fieldType == Boolean.class|| fieldType == boolean.class) {
                field.setBoolean(model,queryResult.getBooleanValue(field.getName()));
            } else if (fieldType == String.class) {
                field.set(model, queryResult.getStringValue(field.getName()));
            }
        }
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

}
 
Example 14
Source File: ExcelReader.java    From azeroth with 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 15
Source File: ExcelReader.java    From jeesuite-libs with 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 16
Source File: SqlHelper.java    From SqliteLookup with Apache License 2.0 4 votes vote down vote up
/**
 * use reflection to parse queryResult's value into model
 * @param queryResult
 * @param model
 */
public static void parseResultSetToModel(ResultSet queryResult,
		Object model) {
	Class<?> clazz = model.getClass();
	Field[] fields = clazz.getDeclaredFields();

	Object fieldVal = null;
	Class<?> fieldType = null;
	try {
		for (Field field : fields) {
			if (field.isAccessible() == false)
				field.setAccessible(true);
			Column column = field.getAnnotation(Column.class);
			if (column == null)
				continue;
			String columnName = column.name();
			fieldVal = queryResult.getValue(columnName);
			fieldType = field.getType();
			if (fieldVal != null) {
				if (fieldType.equals(fieldVal.getClass())) {
					field.set(model, fieldVal);
				} else if (fieldType.equals(short.class)) {
					field.setShort(model,queryResult.getShortValue(columnName));
				} else if (fieldType.equals(Short.class)) {
					field.set(model, (Short) queryResult.getShortValue(columnName));
				} else if (fieldType.equals(int.class)) {
					field.setInt(model,queryResult.getIntValue(columnName));
				} else if (fieldType.equals(Integer.class)) {
					field.set(model, (Integer) queryResult.getIntValue(columnName));
				} else if (fieldType.equals(long.class)) {
					field.setLong(model,
							queryResult.getLongValue(columnName));
				} else if (fieldType.equals(Long.class)) {
					field.set(model, (Long) queryResult
							.getLongValue(columnName));
				} else if (fieldType.equals(float.class)) {
					field.setFloat(model,
							queryResult.getFloatValue(columnName));
				} else if (fieldType.equals(Float.class)) {
					field.set(model, (Float) queryResult
							.getFloatValue(columnName));
				} else if (fieldType.equals(double.class)) {
					field.setDouble(model,
							queryResult.getDoubleValue(columnName));
				} else if (fieldType.equals(Double.class)) {
					field.set(model, (Double) queryResult
							.getDoubleValue(columnName));
				} else if (fieldType.equals(boolean.class)) {
					field.setBoolean(model,
							queryResult.getBooleanValue(columnName));
				} else if (fieldType.equals(Boolean.class)) {
					field.set(model, (Boolean) queryResult
							.getBooleanValue(columnName));
				} else if (fieldType.equals(String.class)) {
					field.set(model,queryResult.getStringValue(columnName));
				} else if(fieldType.equals(Date.class)){
					field.set(model, queryResult.getDateValue(columnName));
				}
			}
		}
	} catch (IllegalAccessException e) {
		e.printStackTrace();
	}
}
 
Example 17
Source File: EntryKeyboardView.java    From bither-android with Apache License 2.0 4 votes vote down vote up
private void setShadowRadius(float radius) throws Exception {
    Field field = KeyboardView.class.getDeclaredField("mShadowRadius");
    field.setAccessible(true);
    field.setFloat(this, radius);
}
 
Example 18
Source File: FieldTest.java    From j2objc with 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 19
Source File: Options.java    From SikuliX1 with MIT License 4 votes vote down vote up
void loadOptions() {
/*
    // public Settings::fields as options
    Field[] fields = Settings.class.getFields();
    Object value = null;
    for (Field field : fields) {
      try {
        Field theField = Settings.class.getField(field.getName());
        value = theField.get(null);
      } catch (NoSuchFieldException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      }
      p("%s (%s) %s", field.getName(), field.getType(), value);
    }
*/
    loadOptions(fnSXOptions);
    if (hasOptions()) {
      testing = isOption("testing", false);
      if (testing) {
        Debug.setDebugLevel(3);
      }
      for (Object oKey : options.keySet()) {
        String sKey = (String) oKey;
        String[] parts = sKey.split("\\.");
        if (parts.length == 1) {
          continue;
        }
        String sClass = parts[0];
        String sAttr = parts[1];
        Class cClass;
        Field cField;
        Class ccField;
        if (sClass.contains("Settings")) {
          try {
            cClass = Class.forName("org.sikuli.basics.Settings");
            cField = cClass.getField(sAttr);
            ccField = cField.getType();
            if (ccField.getName() == "boolean") {
              cField.setBoolean(null, isOption(sKey));
            } else if (ccField.getName() == "int") {
              cField.setInt(null, getOptionInteger(sKey));
            } else if (ccField.getName() == "float") {
              cField.setFloat(null, getOptionFloat(sKey));
            } else if (ccField.getName() == "double") {
              cField.setDouble(null, getOptionDouble(sKey));
            } else if (ccField.getName() == "String") {
              cField.set(null, getOption(sKey));
            }
          } catch (Exception ex) {
            log(-1, "loadOptions: not possible: %s = %s", sKey, options.getProperty(sKey));
          }
        }
      }
    }
  }
 
Example 20
Source File: InstanceStateManager.java    From AndroidCommons with Apache License 2.0 4 votes vote down vote up
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);
}