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

The following examples show how to use java.lang.reflect.Field#setDouble() . 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: AbstractConstraint.java    From GVGAI_GYM with Apache License 2.0 6 votes vote down vote up
/**
 * Set the parameter of the constrains from a HashMap
 * @param parameters	hashmap of constraints parameters
 */
public void setParameters(HashMap<String, Object> parameters){
	Field[] fields = this.getClass().getFields();
	for(Field f:fields){
		for(Entry<String, Object> p:parameters.entrySet()){
			if(f.getName().equalsIgnoreCase(p.getKey())){
				try{
					if(f.getType() == int.class || f.getType() == Integer.class){
						f.setInt(this, Integer.parseInt(p.getValue().toString()));
					}
					else if(f.getType() == double.class || f.getType() == Double.class){
						f.setDouble(this, Double.parseDouble(p.getValue().toString()));
					}
					else{
						f.set(this, f.getType().cast(p.getValue()));
					}
				}
				catch(Exception e){
					e.printStackTrace();	
				}
			}
		}
	}
}
 
Example 3
Source File: Configuration.java    From iDisguise with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
public void loadData() {
	plugin.reloadConfig();
	FileConfiguration fileConfiguration = plugin.getConfig();
	try {
		for(Field pathField : getClass().getDeclaredFields()) {
			if(pathField.getName().endsWith("_PATH")) {
				Field valueField = getClass().getDeclaredField(pathField.getName().substring(0, pathField.getName().length() - 5));
				if(fileConfiguration.isSet((String)pathField.get(null))) {
					if(fileConfiguration.isString((String)pathField.get(null))) {
						valueField.set(this, fileConfiguration.getString((String)pathField.get(null), (String)valueField.get(this)));
					} else if(fileConfiguration.isBoolean((String)pathField.get(null))) {
						valueField.setBoolean(this, fileConfiguration.getBoolean((String)pathField.get(null), valueField.getBoolean(this)));
					} else if(fileConfiguration.isDouble((String)pathField.get(null))) {
						valueField.setDouble(this, fileConfiguration.getDouble((String)pathField.get(null), valueField.getDouble(this)));
					} else if(fileConfiguration.isInt((String)pathField.get(null))) {
						valueField.setInt(this, fileConfiguration.getInt((String)pathField.get(null), valueField.getInt(this)));
					} else if(fileConfiguration.isList((String)pathField.get(null))) {
						valueField.set(this, fileConfiguration.getList((String)pathField.get(null), (List<String>)valueField.get(this)));
					}
				}
			}
		}
	} catch(Exception e) {
		plugin.getLogger().log(Level.SEVERE, "An error occured while loading the config file.", e);
	}
}
 
Example 4
Source File: InfluxDBResultMapper.java    From influxdb-java with MIT License 6 votes vote down vote up
<T> boolean fieldValueForPrimitivesModified(final Class<?> fieldType, final Field field, final T object,
  final Object value) throws IllegalArgumentException, IllegalAccessException {
  if (double.class.isAssignableFrom(fieldType)) {
    field.setDouble(object, ((Double) value).doubleValue());
    return true;
  }
  if (long.class.isAssignableFrom(fieldType)) {
    field.setLong(object, ((Double) value).longValue());
    return true;
  }
  if (int.class.isAssignableFrom(fieldType)) {
    field.setInt(object, ((Double) value).intValue());
    return true;
  }
  if (boolean.class.isAssignableFrom(fieldType)) {
    field.setBoolean(object, Boolean.valueOf(String.valueOf(value)).booleanValue());
    return true;
  }
  return false;
}
 
Example 5
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 6
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 7
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 8
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 9
Source File: ConfigXMLFileReader.java    From ApprovalTests.Java with Apache License 2.0 5 votes vote down vote up
private static void assignField(Field field, HashMap<String, Object> properties) throws IllegalArgumentException, IllegalAccessException
{
  String name = field.getName();
  Object value = properties.get(name);
       if (value == null)                                       {} // do nothing, leave default
  else if (field.getType().isAssignableFrom(String.class))      { field.set(null, value); } 
  else if (field.getType().isAssignableFrom(String[].class))    { field.set(null, value); } 
  else if (field.getType().isAssignableFrom(int.class))         { field.setInt(null, NumberUtils.load((String) value, field.getInt(null))); } 
  else if (field.getType().isAssignableFrom(double.class))      { field.setDouble(null, NumberUtils.load((String) value, field.getDouble(null))); } 
  else if (field.getType().isAssignableFrom(boolean.class))     { field.setBoolean(null, NumberUtils.load((String) value, field.getBoolean(null))); } 
  else                                                          { throw new Error("don't know how to handle field of type " + field.getType().getName());} 
  
}
 
Example 10
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 11
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 12
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 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: FluxResultMapper.java    From influxdb-client-java with MIT License 4 votes vote down vote up
private void setFieldValue(@Nonnull final Object object,
                           @Nullable final Field field,
                           @Nullable final Object value) {

    if (field == null || value == null) {
        return;
    }
    String msg =
        "Class '%s' field '%s' was defined with a different field type and caused a ClassCastException. "
            + "The correct type is '%s' (current field value: '%s').";

    try {
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }
        Class<?> fieldType = field.getType();

        //the same type
        if (fieldType.equals(value.getClass())) {
            field.set(object, value);
            return;
        }

        //convert primitives
        if (double.class.isAssignableFrom(fieldType)) {
            field.setDouble(object, toDoubleValue(value));
            return;
        }
        if (long.class.isAssignableFrom(fieldType)) {
            field.setLong(object, toLongValue(value));
            return;
        }
        if (int.class.isAssignableFrom(fieldType)) {
            field.setInt(object, toIntValue(value));
            return;
        }
        if (boolean.class.isAssignableFrom(fieldType)) {
            field.setBoolean(object, Boolean.valueOf(String.valueOf(value)));
            return;
        }
        if (BigDecimal.class.isAssignableFrom(fieldType)) {
            field.set(object, toBigDecimalValue(value));

            return;
        }

        field.set(object, value);

    } catch (ClassCastException | IllegalAccessException e) {

        throw new InfluxException(String.format(msg, object.getClass().getName(), field.getName(),
            value.getClass().getName(), value));
    }
}
 
Example 15
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 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: WeightedHostScoreScheduler.java    From swift-k with Apache License 2.0 4 votes vote down vote up
public void setProperty(String name, Object value) {
	if (propertyNamesSet.contains(name)) {
		if (POLICY.equals(name)) {
			if (value instanceof String) {
				value = ((String) value).toLowerCase();
			}
			if ("random".equals(value)) {
				policy = POLICY_WEIGHTED_RANDOM;
			}
			else if ("best".equals(value)) {
				policy = POLICY_BEST_SCORE;
			}
			else {
				throw new RuntimeException("Unknown policy type: " + value);
			}
		}
		else if (JOB_THROTTLE.equals(name)) {
			defaultJobThrottle = floatThrottleValue(value);
		}
		else if (DELAY_BASE.equals(name)) {
			defaultDelayBase = TypeUtil.toDouble(value);
		}
		else {
			double val = TypeUtil.toDouble(value);
			try {
				Field f = WeightedHostScoreScheduler.class.getDeclaredField(name);
				if (f.getClass().equals(int.class)) {
					f.setInt(this, (int) val);
				}
				else {
					f.setDouble(this, val);
				}
			}
			catch (Exception e) {
				throw new RuntimeException("Failed to set property '" + name + "'", e);
			}
		}
		updateInternal();
	}
	else {
		super.setProperty(name, value);
	}
}
 
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: FieldTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void testReadWriteStaticField() throws Exception {
  Field f = FieldTest.class.getDeclaredField("staticField");
  assertEquals(Math.PI, f.getDouble(null));
  f.setDouble(this, Math.E);
  assertEquals(Math.E, f.getDouble(null));
}
 
Example 20
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));
          }
        }
      }
    }
  }