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

The following examples show how to use java.lang.reflect.Field#setLong() . 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: FieldTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testSetFinalField() throws Exception {
  Field f = FieldTest.class.getDeclaredField("finalField");
  try {
    f.setLong(this, 10);
    fail("Expected IllegalAccessException");
  } catch (IllegalAccessException e) {
    // expected
  }
  f.setAccessible(true);
  f.setLong(this, 10);
  // The Java compiler will inline access of the field so the change is not visible from normal
  // access. However, in Java the change is visible through a reflective read of the field. We
  // don't test that here because J2ObjC doesn't support it. The final fields are translated to
  // constants and not ivars so the reflective set has no side effect.
  assertEquals(5, finalField);
}
 
Example 2
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 3
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 4
Source File: TestInstanceCloneUtils.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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 5
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 6
Source File: TestPackageInstall.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/**
 * Tests if installing a package with a 0-mtime entry works with java9.
 * see http://bugs.java.com/view_bug.do?bug_id=JDK-8184940
 */
@Test
public void testPackageInstallWith0MtimeZipEntry() throws IOException, RepositoryException, NoSuchFieldException, IllegalAccessException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ZipOutputStream zout = new ZipOutputStream(out);
    Properties p = new Properties();
    p.setProperty("name", TMP_PACKAGE_ID.getName());
    p.setProperty("group", TMP_PACKAGE_ID.getGroup());
    p.setProperty("version", TMP_PACKAGE_ID.getVersionString());
    ZipEntry e = new ZipEntry("META-INF/vault/properties.xml");

    Field field = ZipEntry.class.getDeclaredField("xdostime");
    field.setAccessible(true);
    field.setLong(e, 0);
    zout.putNextEntry(e);
    p.storeToXML(zout, "", "utf-8");
    zout.closeEntry();

    zout.putNextEntry(new ZipEntry("jcr_root/"));
    zout.closeEntry();

    zout.close();
    out.close();

    JcrPackage pack = packMgr.upload(new ByteArrayInputStream(out.toByteArray()), true);
    assertEquals("packageid", TMP_PACKAGE_ID, pack.getDefinition().getId());
}
 
Example 7
Source File: CollectionsDeserializationBenchmark.java    From gson with Apache License 2.0 5 votes vote down vote up
/**
 * This benchmark measures the ideal Gson performance: the cost of parsing a JSON stream and
 * setting object values by reflection. We should strive to reduce the discrepancy between this
 * and {@link #timeCollectionsDefault(int)} .
 */
public void timeCollectionsReflectionStreaming(int reps) throws Exception {
  for (int i=0; i<reps; ++i) {
    StringReader reader = new StringReader(json);
    JsonReader jr = new JsonReader(reader);
    jr.beginArray();
    List<BagOfPrimitives> bags = new ArrayList<BagOfPrimitives>();
    while(jr.hasNext()) {
      jr.beginObject();
      BagOfPrimitives bag = new BagOfPrimitives();
      while(jr.hasNext()) {
        String name = jr.nextName();
        for (Field field : BagOfPrimitives.class.getDeclaredFields()) {
          if (field.getName().equals(name)) {
            Class<?> fieldType = field.getType();
            if (fieldType.equals(long.class)) {
              field.setLong(bag, jr.nextLong());
            } else if (fieldType.equals(int.class)) {
              field.setInt(bag, jr.nextInt());
            } else if (fieldType.equals(boolean.class)) {
              field.setBoolean(bag, jr.nextBoolean());
            } else if (fieldType.equals(String.class)) {
              field.set(bag, jr.nextString());
            } else {
              throw new RuntimeException("Unexpected: type: " + fieldType + ", name: " + name);
            }
          }
        }
      }
      jr.endObject();
      bags.add(bag);
    }
    jr.endArray();
  }
}
 
Example 8
Source File: BagOfPrimitivesDeserializationBenchmark.java    From gson with Apache License 2.0 5 votes vote down vote up
/**
 * This benchmark measures the ideal Gson performance: the cost of parsing a JSON stream and
 * setting object values by reflection. We should strive to reduce the discrepancy between this
 * and {@link #timeBagOfPrimitivesDefault(int)} .
 */
public void timeBagOfPrimitivesReflectionStreaming(int reps) throws Exception {
  for (int i=0; i<reps; ++i) {
    StringReader reader = new StringReader(json);
    JsonReader jr = new JsonReader(reader);
    jr.beginObject();
    BagOfPrimitives bag = new BagOfPrimitives();
    while(jr.hasNext()) {
      String name = jr.nextName();
      for (Field field : BagOfPrimitives.class.getDeclaredFields()) {
        if (field.getName().equals(name)) {
          Class<?> fieldType = field.getType();
          if (fieldType.equals(long.class)) {
            field.setLong(bag, jr.nextLong());
          } else if (fieldType.equals(int.class)) {
            field.setInt(bag, jr.nextInt());
          } else if (fieldType.equals(boolean.class)) {
            field.setBoolean(bag, jr.nextBoolean());
          } else if (fieldType.equals(String.class)) {
            field.set(bag, jr.nextString());
          } else {
            throw new RuntimeException("Unexpected: type: " + fieldType + ", name: " + name);
          }
        }
      }
    }
    jr.endObject();
  }
}
 
Example 9
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 10
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 11
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 12
Source File: Prefs.java    From AndroidRipper with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void updateValue (Field parameter) throws IllegalArgumentException, IllegalAccessException {
	Log.v("androidripper", "Updating value " + parameter.getName());
	Class<?> type = parameter.getType();
	String before = (parameter.get("") != null)?parameter.get("").toString():null;
	if (type.equals(int.class)) {
		parameter.setInt (parameter, getInt (parameter));
	} else if (type.equals(long.class)) {
		parameter.setLong (parameter, getLong (parameter));
	} else if (type.equals(String.class)) {
		parameter.set (parameter, getString (parameter));
	} else if (type.equals(boolean.class)) {
		parameter.setBoolean (parameter, getBoolean (parameter));
	} else if (type.isArray()) {
		setArray (parameter, type);
	} else {
		return;
	}
	Object o = parameter.get("");
	String after = (o==null)?"null":o.toString();
	if (!after.equals(before)) {
		if (!type.isArray()) {
			Log.d("androidripper", "Updated value of parameter " + parameter.getName() + " to " + after + " (default = " + before + ")");
		} else {
			Log.d("androidripper", "Updated values of array parameter " + parameter.getName());
		}
	}
}
 
Example 13
Source File: DBObject.java    From GLEXP-Team-onebillion with Apache License 2.0 5 votes vote down vote up
private void setLongField(String name, long value)
{
    try {
        Field field = this.getClass().getDeclaredField(name);
        field.setLong(this, value);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example 14
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 15
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 16
Source File: Persisted.java    From commcare-android with Apache License 2.0 4 votes vote down vote up
private static void readVal(Field f, Object o, DataInputStream in)
        throws DeserializationException, IOException, IllegalAccessException {
    synchronized (f) {
        // 'f' is a cached field: sync access across threads
        Persisting p = f.getAnnotation(Persisting.class);
        Class type = f.getType();
        try {
            f.setAccessible(true);

            if (type.equals(String.class)) {
                String read = ExtUtil.readString(in);
                f.set(o, p.nullable() ? ExtUtil.nullIfEmpty(read) : read);
                return;
            } else if (type.equals(Integer.TYPE)) {
                //Primitive Integers
                f.setInt(o, ExtUtil.readInt(in));
                return;
            } else if (type.equals(Long.TYPE)) {
              f.setLong(o, ExtUtil.readLong(in));
              return;
            } else if (type.equals(Date.class)) {
                f.set(o, ExtUtil.readDate(in));
                return;
            } else if (type.isArray()) {
                //We only support byte arrays for now
                if (type.getComponentType().equals(Byte.TYPE)) {
                    f.set(o, ExtUtil.readBytes(in));
                    return;
                }
            } else if (type.equals(Boolean.TYPE)) {
                f.setBoolean(o, ExtUtil.readBool(in));
                return;
            }
        } finally {
            f.setAccessible(false);
        }

        //By Default
        throw new DeserializationException("Couldn't read persisted type " + f.getType().toString());
    }
}
 
Example 17
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);
}
 
Example 18
Source File: ConfigUtils.java    From AACAdditionPro with GNU General Public License v3.0 4 votes vote down vote up
/**
 * This will process the {@link LoadFromConfiguration} annotation to load all config values.
 *
 * @param object  the object in which the config values should be loaded.
 * @param prePath the first path of the part (e.g. helpful when using {@link Module#getConfigString()})
 */
public static void processLoadFromConfiguration(final Object object, String prePath)
{
    // Config-Annotation processing
    LoadFromConfiguration annotation;
    for (Field field : object.getClass().getDeclaredFields()) {
        // Load the annotation and check if it is present.
        annotation = field.getAnnotation(LoadFromConfiguration.class);

        if (annotation == null) {
            continue;
        }

        // Make it possible to modify the field
        field.setAccessible(true);

        // Get the full config path.
        String path = annotation.configPath();

        if (prePath != null) {
            path = prePath + path;
        }

        // Get the type of the field.
        final Class type = field.getType();

        // The different classes
        try {
            // Boolean
            if (type == boolean.class || type == Boolean.class) {
                field.setBoolean(object, AACAdditionPro.getInstance().getConfig().getBoolean(path));
            }
            // Numbers
            else if (type == double.class || type == Double.class) {
                field.setDouble(object, AACAdditionPro.getInstance().getConfig().getDouble(path));
            } else if (type == int.class || type == Integer.class) {
                field.setInt(object, AACAdditionPro.getInstance().getConfig().getInt(path));
            } else if (type == long.class || type == Long.class) {
                field.setLong(object, AACAdditionPro.getInstance().getConfig().getLong(path));
            } else if (type == String.class) {
                field.set(object, AACAdditionPro.getInstance().getConfig().getString(path));
            }
            // Special stuff
            else if (type == ItemStack.class) {
                field.set(object, AACAdditionPro.getInstance().getConfig().getItemStack(path));
            } else if (type == Color.class) {
                field.set(object, AACAdditionPro.getInstance().getConfig().getColor(path));
            } else if (type == OfflinePlayer.class) {
                field.set(object, AACAdditionPro.getInstance().getConfig().getOfflinePlayer(path));
            } else if (type == Vector.class) {
                field.set(object, AACAdditionPro.getInstance().getConfig().getVector(path));
            }
            // Lists
            else if (type == List.class) {
                // StringLists
                if (annotation.listType() == String.class) {
                    field.set(object, ConfigUtils.loadStringOrStringList(path));

                    // Unknown type
                } else {
                    field.set(object, AACAdditionPro.getInstance().getConfig().getList(path));
                }

            }
            // No special type found
            else {
                field.set(object, AACAdditionPro.getInstance().getConfig().get(path));
            }
        } catch (IllegalAccessException e) {
            AACAdditionPro.getInstance().getLogger().log(Level.SEVERE, "Unable to load config value due to unknown type.", e);
        }
    }
}
 
Example 19
Source File: QueueControlTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testRemoveAllWithPagingMode() throws Exception {

   final int MESSAGE_SIZE = 1024 * 3; // 3k

   // reset maxSize for Paging mode
   Field maxSizField = PagingManagerImpl.class.getDeclaredField("maxSize");
   maxSizField.setAccessible(true);
   maxSizField.setLong(server.getPagingManager(), 10240);
   clearDataRecreateServerDirs();

   SimpleString address = RandomUtil.randomSimpleString();
   SimpleString queueName = RandomUtil.randomSimpleString();

   session.createQueue(new QueueConfiguration(queueName).setAddress(address).setDurable(durable));

   Queue queue = server.locateQueue(queueName);
   Assert.assertFalse(queue.getPageSubscription().isPaging());

   ClientProducer producer = session.createProducer(address);

   byte[] body = new byte[MESSAGE_SIZE];

   ByteBuffer bb = ByteBuffer.wrap(body);

   for (int j = 1; j <= MESSAGE_SIZE; j++) {
      bb.put(getSamplebyte(j));
   }

   final int numberOfMessages = 8000;
   ClientMessage message;
   for (int i = 0; i < numberOfMessages; i++) {
      message = session.createMessage(true);

      ActiveMQBuffer bodyLocal = message.getBodyBuffer();

      bodyLocal.writeBytes(body);

      producer.send(message);
   }

   Assert.assertTrue(queue.getPageSubscription().isPaging());

   QueueControl queueControl = createManagementControl(address, queueName);
   assertMessageMetrics(queueControl, numberOfMessages, durable);
   int removedMatchedMessagesCount = queueControl.removeAllMessages();
   Assert.assertEquals(numberOfMessages, removedMatchedMessagesCount);
   assertMessageMetrics(queueControl, 0, durable);

   Field queueMemoprySizeField = QueueImpl.class.getDeclaredField("queueMemorySize");
   queueMemoprySizeField.setAccessible(true);
   AtomicInteger queueMemorySize = (AtomicInteger) queueMemoprySizeField.get(queue);
   Assert.assertEquals(0, queueMemorySize.get());

   session.deleteQueue(queueName);
}
 
Example 20
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));
        }
    }
}