private boolean unpackPrimitive(final Field afield, InputObjectState os) { try { // TODO arrays if (afield.getType().equals(Boolean.TYPE)) afield.setBoolean(_theObject, os.unpackBoolean()); else if (afield.getType().equals(Byte.TYPE)) afield.setByte(_theObject, os.unpackByte()); else if (afield.getType().equals(Short.TYPE)) afield.setShort(_theObject, os.unpackShort()); else if (afield.getType().equals(Integer.TYPE)) afield.setInt(_theObject, os.unpackInt()); else if (afield.getType().equals(Long.TYPE)) afield.setLong(_theObject, os.unpackLong()); else if (afield.getType().equals(Float.TYPE)) afield.setFloat(_theObject, os.unpackFloat()); else if (afield.getType().equals(Double.TYPE)) afield.setDouble(_theObject, os.unpackDouble()); else if (afield.getType().equals(Character.TYPE)) afield.setChar(_theObject, os.unpackChar()); else return false; } catch (final IOException ex) { ex.printStackTrace(); return false; } catch (final Exception ex) { ex.printStackTrace(); return false; } return true; }
/** * Creates a new entity * * @param instantiationValues A Map containing the values to set for this new entity. */ protected ActiveRecordBase(Map<String, Object> instantiationValues) { super(); try { Map<String, Field> classFields = EntitiesHelper.getFieldsMap(getClass()); for (String key : instantiationValues.keySet()) { if (classFields.containsKey(key)) { Field field = classFields.get(key); Class fieldClass = field.getClass(); Object data = instantiationValues.get(key); if (fieldClass == Integer.class) { field.setInt(this, ((Integer) data).intValue()); } else if (fieldClass == Byte.class) { field.setByte(this, ((Byte) data).byteValue()); } else if (fieldClass == Short.class) { field.setShort(this, ((Short) data).shortValue()); } else if (fieldClass == Long.class) { field.setLong(this, ((Long) data).longValue()); } else if (fieldClass == Double.class) { field.setDouble(this, ((Double) data).doubleValue()); } else if (fieldClass == Boolean.class) { field.setBoolean(this, ((Boolean) data).booleanValue()); } else { field.set(this, data); } } } } catch (IllegalAccessException e) { // TODO: Fixme } }
private final void map(Object value, Object result, java.lang.reflect.Field member) throws IllegalAccessException { Class<?> mType = member.getType(); if (mType.isPrimitive()) { if (mType == byte.class) { member.setByte(result, (Byte) value); } else if (mType == short.class) { member.setShort(result, (Short) value); } else if (mType == int.class) { member.setInt(result, (Integer) value); } else if (mType == long.class) { member.setLong(result, (Long) value); } else if (mType == float.class) { member.setFloat(result, (Float) value); } else if (mType == double.class) { member.setDouble(result, (Double) value); } else if (mType == boolean.class) { member.setBoolean(result, (Boolean) value); } else if (mType == char.class) { member.setChar(result, (Character) value); } } else { member.set(result, value); } }
public static void toggleField(Field field, Object obj, boolean on) throws IllegalAccessException, InstantiationException { field.setAccessible(true); if (field.getType() == String.class) { field.set(obj, on ? TEST_STRING_VAL1 : TEST_STRING_VAL2); } else if (field.getType() == boolean.class) { field.setBoolean(obj, on ? true : false); } else if (field.getType() == short.class) { field.setShort(obj, on ? (short) 1 : (short) 0); } else if (field.getType() == long.class) { field.setLong(obj, on ? 1 : 0); } else if (field.getType() == float.class) { field.setFloat(obj, on ? 1 : 0); } else if (field.getType() == int.class) { field.setInt(obj, on ? 1 : 0); } else if (field.getType() == Integer.class) { field.set(obj, on ? 1 : 0); } else if (field.getType() == byte.class) { field.setByte(obj, on ? (byte) 1 : (byte) 0); } else if (field.getType() == char.class) { field.setChar(obj, on ? (char) 1 : (char) 0); } else if (field.getType() == double.class) { field.setDouble(obj, on ? 1 : 0); } else if (field.getType() == BigDecimal.class) { field.set(obj, on ? new BigDecimal(1) : new BigDecimal(0)); } else if (field.getType() == Date.class) { field.set(obj, on ? new Date() : new Date(0)); } else if (field.getType().isEnum()) { field.set(obj, field.getType().getEnumConstants()[on ? 1 : 0]); } else if (Object.class.isAssignableFrom(field.getType())) { field.set(obj, field.getType().newInstance()); } else { fail("Don't know how to set a " + field.getType().getName()); } }
public void deserialize(JsonObject jo, Object t, Field field) throws IllegalAccessException { if (jo.has(field.getName())) { Short s = jo.getAsJsonPrimitive(field.getName()).getAsShort(); field.setShort(t, s); } }
public static void keep_readShort(Parcel paramParcel, Field paramField, Object paramObject) { try { paramField.setShort(paramObject, (short) paramParcel.readInt()); return; } catch (Exception paramParcel) { v.e("MicroMsg.MCacheItem", "exception:%s", new Object[] {be.f(paramParcel)}); } }
void deserialize(AbstractHessianInput in, Object obj) throws IOException { int value = 0; try { value = in.readInt(); _field.setShort(obj, (short) value); } catch (Exception e) { logDeserializeError(_field, obj, value, e); } }
public static void main(String[] ag) throws IllegalAccessException, InstantiationException, NoSuchFieldException { Class clazz = SubTopic.class; SubTopic subTopic = (SubTopic) clazz.newInstance(); Field field = clazz.getDeclaredField("role"); field.setAccessible(true); field.setShort(subTopic, (short) 1); field.get(subTopic); }
public static void assertMeetsHashCodeContract(Class<?> classUnderTest, String[] fieldNames) { try { Field[] fields = getFieldsByNameOrAll(classUnderTest, fieldNames); for (int i = 0; i < fields.length; i++) { Object o1 = classUnderTest.newInstance(); int initialHashCode = o1.hashCode(); Field field = fields[i]; field.setAccessible(true); if (field.getType() == String.class) { field.set(o1, TEST_STRING_VAL1); } else if (field.getType() == boolean.class) { field.setBoolean(o1, true); } else if (field.getType() == short.class) { field.setShort(o1, (short) 1); } else if (field.getType() == long.class) { field.setLong(o1, (long) 1); } else if (field.getType() == float.class) { field.setFloat(o1, (float) 1); } else if (field.getType() == int.class) { field.setInt(o1, 1); } else if (field.getType() == byte.class) { field.setByte(o1, (byte) 1); } else if (field.getType() == char.class) { field.setChar(o1, (char) 1); } else if (field.getType() == double.class) { field.setDouble(o1, (double) 1); } else if (field.getType().isEnum()) { field.set(o1, field.getType().getEnumConstants()[0]); } else if (Object.class.isAssignableFrom(field.getType())) { field.set(o1, field.getType().newInstance()); } else { fail("Don't know how to set a " + field.getType().getName()); } int updatedHashCode = o1.hashCode(); assertFalse( "The field " + field.getName() + " was not taken into account for the hashCode contract ", initialHashCode == updatedHashCode); } } catch (InstantiationException e) { e.printStackTrace(); throw new AssertionError("Unable to construct an instance of the class under test"); } catch (IllegalAccessException e) { e.printStackTrace(); throw new AssertionError("Unable to construct an instance of the class under test"); } catch (NoSuchFieldException e) { e.printStackTrace(); throw new AssertionError("Unable to find field in the class under test"); } }
protected void readFields0( final Object object, final Class classs, final ObjectInputStream objectInputStream) throws IllegalAccessException { final Set<Field> serializableFields = ReflectionHelper.buildSerializableFields(object, classs); // serialize fields in alphabetical order final Iterator<Field> iterator = serializableFields.iterator(); while (iterator.hasNext()) { final Field field = iterator.next(); field.setAccessible(true); final Class fieldType = field.getType(); if (fieldType.equals(Boolean.TYPE)) { field.setBoolean(object, objectInputStream.readBoolean()); continue; } if (fieldType.equals(Byte.TYPE)) { field.setByte(object, objectInputStream.readByte()); continue; } if (fieldType.equals(Short.TYPE)) { field.setShort(object, objectInputStream.readShort()); continue; } if (fieldType.equals(Integer.TYPE)) { field.setInt(object, objectInputStream.readInt()); continue; } if (fieldType.equals(Long.TYPE)) { field.setLong(object, objectInputStream.readLong()); continue; } if (fieldType.equals(Float.TYPE)) { field.setFloat(object, objectInputStream.readFloat()); continue; } if (fieldType.equals(Double.TYPE)) { field.setDouble(object, objectInputStream.readDouble()); continue; } if (fieldType.equals(Character.TYPE)) { field.setChar(object, objectInputStream.readChar()); continue; } field.set(object, objectInputStream.readObject()); } final Class superType = classs.getSuperclass(); if (false == superType.equals(Object.class)) { this.readFields(object, superType, objectInputStream); } }
private void configureField(Object check, Field field, String value) { try { field.setAccessible(true); if (field.getType().equals(String.class)) { field.set(check, value); } else if ("int".equals(field.getType().getSimpleName())) { field.setInt(check, Integer.parseInt(value)); } else if ("short".equals(field.getType().getSimpleName())) { field.setShort(check, Short.parseShort(value)); } else if ("long".equals(field.getType().getSimpleName())) { field.setLong(check, Long.parseLong(value)); } else if ("double".equals(field.getType().getSimpleName())) { field.setDouble(check, Double.parseDouble(value)); } else if ("boolean".equals(field.getType().getSimpleName())) { field.setBoolean(check, Boolean.parseBoolean(value)); } else if ("byte".equals(field.getType().getSimpleName())) { field.setByte(check, Byte.parseByte(value)); } else if (field.getType().equals(Integer.class)) { field.set(check, Integer.parseInt(value)); } else if (field.getType().equals(Long.class)) { field.set(check, Long.parseLong(value)); } else if (field.getType().equals(Double.class)) { field.set(check, Double.parseDouble(value)); } else if (field.getType().equals(Boolean.class)) { field.set(check, Boolean.parseBoolean(value)); } else { throw new SonarException( "The type of the field " + field + " is not supported: " + field.getType()); } } catch (IllegalAccessException e) { throw new SonarException( "Can not set the value of the field " + field + " in the class: " + check.getClass().getName(), e); } }
public static void reflectionsetvalue( Field f, TileEntity tileEntity, ByteArrayDataInput dat, String fieldname) { try { if (f.getType().equals(Integer.TYPE)) f.setInt(tileEntity, Integer.parseInt(dat.readUTF())); if (f.getType().equals(Boolean.TYPE)) f.setBoolean(tileEntity, Boolean.parseBoolean(dat.readUTF())); if (f.getType().equals(Short.TYPE)) f.setShort(tileEntity, Short.parseShort(dat.readUTF())); if (f.getType().equals(Float.TYPE)) f.setFloat(tileEntity, Float.parseFloat(dat.readUTF())); if (f.getType().equals(String.class)) f.set(tileEntity, dat.readUTF()); if ((tileEntity instanceof INetworkHandlerListener)) { ((INetworkHandlerListener) tileEntity).onNetworkHandlerUpdate(fieldname); } } catch (Exception e) { } }
/** * 设置对象的指定属性值 * * @param obj * @param fieldName * @param value */ public static void setAttributeValue(Object obj, int index, Cursor cursor) { try { String fieldName = cursor.getColumnName(index); Field field = obj.getClass().getField(fieldName); Class<?> clazz = field.getType(); if (clazz.isPrimitive()) { if (Short.TYPE == clazz) { field.setShort(obj, cursor.getShort(index)); } else if (Integer.TYPE == clazz) { field.setInt(obj, cursor.getInt(index)); } else if (Long.TYPE == clazz) { field.setLong(obj, cursor.getLong(index)); } else if (Float.TYPE == clazz) { field.setFloat(obj, cursor.getFloat(index)); } else if (Double.TYPE == clazz) { field.setDouble(obj, cursor.getDouble(index)); } } else if (clazz.isArray()) { field.set(obj, cursor.getBlob(index)); } else if (Integer.class == clazz) { field.set(obj, Integer.valueOf(cursor.getInt(index))); } else if (Long.class == clazz) { field.set(obj, Long.valueOf(cursor.getLong(index))); } else if (Float.class == clazz) { field.set(obj, Float.valueOf(cursor.getFloat(index))); } else if (Double.class == clazz) { field.set(obj, Double.valueOf(cursor.getDouble(index))); } else if (String.class == clazz) { field.set(obj, cursor.getString(index)); } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }
public static void setField(Field f, Object o, String t) throws NumberFormatException, IllegalArgumentException, IllegalAccessException { Class type = f.getType(); if (String.class.equals(type)) { f.set(o, t); } else if (Double.class.equals(type)) { f.set(o, Double.valueOf(t)); } else if (Float.class.equals(type)) { f.set(o, Float.valueOf(t)); } else if (Long.class.equals(type)) { f.set(o, Long.valueOf(t)); } else if (Integer.class.equals(type)) { f.set(o, Integer.valueOf(t)); } else if (Character.class.equals(type)) { f.set(o, Character.valueOf(t.charAt(0))); } else if (Short.class.equals(type)) { f.set(o, Short.valueOf(t)); } else if (Byte.class.equals(type)) { f.set(o, Byte.valueOf(t)); } else if (Boolean.class.equals(type)) { f.set(o, Boolean.valueOf(t)); } else if (Double.TYPE.equals(type)) { f.setDouble(o, Double.parseDouble(t)); } else if (Float.TYPE.equals(type)) { f.setFloat(o, Float.parseFloat(t)); } else if (Long.TYPE.equals(type)) { f.setLong(o, Long.parseLong(t)); } else if (Integer.TYPE.equals(type)) { f.setInt(o, Integer.parseInt(t)); } else if (Character.TYPE.equals(type)) { f.setChar(o, t.charAt(0)); } else if (Short.TYPE.equals(type)) { f.setShort(o, Short.parseShort(t)); } else if (Byte.TYPE.equals(type)) { f.setByte(o, Byte.parseByte(t)); } else if (Boolean.TYPE.equals(type)) { f.setBoolean(o, Boolean.parseBoolean(t)); } }
@SuppressWarnings("rawtypes") public void updateFromData( Object obj, ByteBuffer byteBuffer, float[] floatValues, String[] stringValues, Indexes index) throws IllegalArgumentException, IllegalAccessException { Reporter r = null; if (BuildCraftCore.trackNetworkUsage) { if (!report.containsKey(clas.getName())) report.put(clas.getName(), new Reporter()); r = report.get(clas.getName()); r.clas = clas; } else r = new Reporter(); r.occurences++; for (Field f : shortFields) { f.setShort(obj, byteBuffer.readShort()); r.bytes += 2; r.dataInt += 1; } for (Field f : intFields) { f.setInt(obj, byteBuffer.readInt()); r.bytes += 4; r.dataInt += 1; } for (Field f : booleanFields) { f.setBoolean(obj, byteBuffer.readUnsignedByte() == 1); r.bytes += 1; r.dataInt += 1; } for (Field f : enumFields) { f.set(obj, ((Class) f.getGenericType()).getEnumConstants()[byteBuffer.readUnsignedByte()]); r.bytes += 1; r.dataInt += 1; } for (Field f : unsignedByteFields) { f.setInt(obj, byteBuffer.readUnsignedByte()); r.bytes += 1; r.dataInt += 1; } for (Field f : floatFields) { f.setFloat(obj, floatValues[index.floatIndex]); index.floatIndex++; r.bytes += 4; r.dataFloat += 1; } for (Field f : doubleFields) { f.setDouble(obj, floatValues[index.floatIndex]); index.floatIndex++; r.bytes += 4; r.dataFloat += 1; } for (Field f : stringFields) { f.set(obj, stringValues[index.stringIndex]); r.bytes += stringValues[index.stringIndex].length(); index.stringIndex++; r.dataString += 1; } for (ClassMapping c : objectFields) { boolean isNull = byteBuffer.readUnsignedByte() == 0; r.bytes += 1; r.dataInt += 1; if (isNull) { for (int i = 0; i < c.sizeBytes; ++i) byteBuffer.readUnsignedByte(); index.floatIndex += c.sizeFloat; index.stringIndex += c.sizeString; } else c.updateFromData(c.field.get(obj), byteBuffer, floatValues, stringValues, index); } for (Field f : doubleArrayFields) { TileNetworkData updateAnnotation = f.getAnnotation(TileNetworkData.class); for (int i = 0; i < updateAnnotation.staticSize(); ++i) { ((double[]) f.get(obj))[i] = floatValues[index.floatIndex]; index.floatIndex++; r.bytes += 4; r.dataFloat += 1; } } for (Field f : shortArrayFields) { TileNetworkData updateAnnotation = f.getAnnotation(TileNetworkData.class); for (int i = 0; i < updateAnnotation.staticSize(); ++i) { ((short[]) f.get(obj))[i] = byteBuffer.readShort(); r.bytes += 2; r.dataInt += 1; } } for (Field f : intArrayFields) { TileNetworkData updateAnnotation = f.getAnnotation(TileNetworkData.class); for (int i = 0; i < updateAnnotation.staticSize(); ++i) { ((int[]) f.get(obj))[i] = byteBuffer.readInt(); r.bytes += 4; r.dataInt += 1; } } for (Field f : booleanArrayFields) { TileNetworkData updateAnnotation = f.getAnnotation(TileNetworkData.class); for (int i = 0; i < updateAnnotation.staticSize(); ++i) { ((boolean[]) f.get(obj))[i] = byteBuffer.readUnsignedByte() == 1; r.bytes += 1; r.dataInt += 1; } } for (Field f : unsignedByteArrayFields) { TileNetworkData updateAnnotation = f.getAnnotation(TileNetworkData.class); for (int i = 0; i < updateAnnotation.staticSize(); ++i) { ((int[]) f.get(obj))[i] = byteBuffer.readUnsignedByte(); r.bytes += 1; r.dataInt += 1; } } for (Field f : stringArrayFields) { TileNetworkData updateAnnotation = f.getAnnotation(TileNetworkData.class); String[] strs = (String[]) f.get(obj); for (int i = 0; i < updateAnnotation.staticSize(); ++i) { strs[i] = stringValues[index.stringIndex]; r.bytes += stringValues[index.stringIndex].length(); index.stringIndex++; r.dataString += 1; } } for (ClassMapping c : objectArrayFields) { TileNetworkData updateAnnotation = c.field.getAnnotation(TileNetworkData.class); Object[] cpts = (Object[]) c.field.get(obj); for (int i = 0; i < updateAnnotation.staticSize(); ++i) { boolean isNull = byteBuffer.readUnsignedByte() == 0; r.bytes += 1; r.dataInt += 1; if (isNull) { for (int j = 0; j < c.sizeBytes; ++j) byteBuffer.readUnsignedByte(); index.floatIndex += c.sizeFloat; index.stringIndex += c.sizeString; } else c.updateFromData(cpts[i], byteBuffer, floatValues, stringValues, index); } } }
void setShort(Object obj, short s) throws IllegalArgumentException, IllegalAccessException { javaField.setShort(obj, s); }
@Override protected <T> void handleClonePrimitiveField( T obj, T copy, CloneDriver driver, FieldModel<T> f, IdentityHashMap<Object, Object> referencesToReuse) { Field field = f.getField(); try { Class<?> clazz = f.getFieldClass(); if (f.isPrivate()) { if (java.lang.Boolean.TYPE == clazz) { field.setBoolean(copy, field.getBoolean(obj)); } else if (java.lang.Byte.TYPE == clazz) { field.setByte(copy, field.getByte(obj)); } else if (java.lang.Character.TYPE == clazz) { field.setChar(copy, field.getChar(obj)); } else if (java.lang.Short.TYPE == clazz) { field.setShort(copy, field.getShort(obj)); } else if (java.lang.Integer.TYPE == clazz) { field.setInt(copy, field.getInt(obj)); } else if (java.lang.Long.TYPE == clazz) { field.setLong(copy, field.getLong(obj)); } else if (java.lang.Float.TYPE == clazz) { field.setFloat(copy, field.getFloat(obj)); } else if (java.lang.Double.TYPE == clazz) { field.setDouble(copy, field.getDouble(obj)); } else { throw new IllegalStateException("Expected primitive but was :" + clazz.getName()); } } else { if (java.lang.Boolean.TYPE == clazz) { f.getFieldAccess().putBooleanValue(copy, field.getBoolean(obj)); } else if (java.lang.Byte.TYPE == clazz) { f.getFieldAccess().putByteValue(copy, field.getByte(obj)); } else if (java.lang.Character.TYPE == clazz) { f.getFieldAccess().putCharValue(copy, field.getChar(obj)); } else if (java.lang.Short.TYPE == clazz) { f.getFieldAccess().putShortValue(copy, field.getShort(obj)); } else if (java.lang.Integer.TYPE == clazz) { f.getFieldAccess().putIntValue(copy, field.getInt(obj)); } else if (java.lang.Long.TYPE == clazz) { f.getFieldAccess().putLongValue(copy, field.getLong(obj)); } else if (java.lang.Float.TYPE == clazz) { f.getFieldAccess().putFloatValue(copy, field.getFloat(obj)); } else if (java.lang.Double.TYPE == clazz) { f.getFieldAccess().putDoubleValue(copy, field.getDouble(obj)); } else { throw new IllegalStateException("Expected primitive but was :" + clazz.getName()); } } } catch (IllegalArgumentException e) { throw new IllegalStateException( "Problem performing clone for field {" + field.getName() + "} of object {" + System.identityHashCode(obj) + "}: " + e.getMessage(), e); } catch (IllegalAccessException e) { throw new IllegalStateException( "Problem performing clone for field {" + field.getName() + "} of object {" + System.identityHashCode(obj) + "}: " + e.getMessage(), e); } }
/** * Parses object with follow rules: * * <p>1. All fields should had a public access. 2. The name of the filed should be fully equal to * name of JSONObject key. 3. Supports parse of all Java primitives, all {@link String}, arrays of * primitive types, {@link String}s and {@link com.vk.sdk.api.model.VKApiModel}s, list * implementation line {@link VKList}, {@link com.vk.sdk.api.model.VKAttachments.VKAttachment} or * {@link com.vk.sdk.api.model.VKPhotoSizes}, {@link com.vk.sdk.api.model.VKApiModel}s. * * <p>4. Boolean fields defines by vk_int == 1 expression. * * @param object object to initialize * @param source data to read values * @param <T> type of result * @return initialized according with given data object * @throws org.json.JSONException if source object structure is invalid */ @SuppressWarnings({"rawtypes", "unchecked"}) public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException { if (source.has("response")) { source = source.optJSONObject("response"); } if (source == null) { return object; } for (Field field : object.getClass().getFields()) { field.setAccessible(true); String fieldName = field.getName(); Class<?> fieldType = field.getType(); Object value = source.opt(fieldName); if (value == null) { continue; } try { if (fieldType.isPrimitive() && value instanceof Number) { Number number = (Number) value; if (fieldType.equals(int.class)) { field.setInt(object, number.intValue()); } else if (fieldType.equals(long.class)) { field.setLong(object, number.longValue()); } else if (fieldType.equals(float.class)) { field.setFloat(object, number.floatValue()); } else if (fieldType.equals(double.class)) { field.setDouble(object, number.doubleValue()); } else if (fieldType.equals(boolean.class)) { field.setBoolean(object, number.intValue() == 1); } else if (fieldType.equals(short.class)) { field.setShort(object, number.shortValue()); } else if (fieldType.equals(byte.class)) { field.setByte(object, number.byteValue()); } } else { Object result = field.get(object); if (value.getClass().equals(fieldType)) { result = value; } else if (fieldType.isArray() && value instanceof JSONArray) { result = parseArrayViaReflection((JSONArray) value, fieldType); } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) { Constructor<?> constructor = fieldType.getConstructor(JSONArray.class); result = constructor.newInstance((JSONArray) value); } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) { Constructor<?> constructor = fieldType.getConstructor(JSONArray.class); result = constructor.newInstance((JSONArray) value); } else if (VKList.class.equals(fieldType)) { ParameterizedType genericTypes = (ParameterizedType) field.getGenericType(); Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0]; if (VKApiModel.class.isAssignableFrom(genericType) && Parcelable.class.isAssignableFrom(genericType) && Identifiable.class.isAssignableFrom(genericType)) { if (value instanceof JSONArray) { result = new VKList((JSONArray) value, genericType); } else if (value instanceof JSONObject) { result = new VKList((JSONObject) value, genericType); } } } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) { result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value); } field.set(object, result); } } catch (InstantiationException e) { throw new JSONException(e.getMessage()); } catch (IllegalAccessException e) { throw new JSONException(e.getMessage()); } catch (NoSuchMethodException e) { throw new JSONException(e.getMessage()); } catch (InvocationTargetException e) { throw new JSONException(e.getMessage()); } catch (NoSuchMethodError e) { // Примечание Виталия: // Вы не поверите, но у некоторых вендоров getFields() вызывает ВОТ ЭТО. // Иногда я всерьез задумываюсь, правильно ли я поступил, выбрав Android в качестве // платформы разработки. throw new JSONException(e.getMessage()); } } return object; }
public static void assertMeetsEqualsContract(Class<?> classUnderTest, String[] fieldNames) { Object o1; Object o2; try { // Get Instances o1 = classUnderTest.newInstance(); o2 = classUnderTest.newInstance(); assertTrue("Instances with default constructor not equal (o1.equals(o2))", o1.equals(o2)); assertTrue("Instances with default constructor not equal (o2.equals(o1))", o2.equals(o1)); Field[] fields = getFieldsByNameOrAll(classUnderTest, fieldNames); for (int i = 0; i < fields.length; i++) { // Reset the instances o1 = classUnderTest.newInstance(); o2 = classUnderTest.newInstance(); Field field = fields[i]; field.setAccessible(true); if (field.getType() == String.class) { field.set(o1, TEST_STRING_VAL1); } else if (field.getType() == boolean.class) { field.setBoolean(o1, true); } else if (field.getType() == short.class) { field.setShort(o1, (short) 1); } else if (field.getType() == long.class) { field.setLong(o1, (long) 1); } else if (field.getType() == float.class) { field.setFloat(o1, (float) 1); } else if (field.getType() == int.class) { field.setInt(o1, 1); } else if (field.getType() == byte.class) { field.setByte(o1, (byte) 1); } else if (field.getType() == char.class) { field.setChar(o1, (char) 1); } else if (field.getType() == double.class) { field.setDouble(o1, (double) 1); } else if (field.getType().isEnum()) { field.set(o1, field.getType().getEnumConstants()[0]); } else if (Object.class.isAssignableFrom(field.getType())) { field.set(o1, field.getType().newInstance()); } else { fail("Don't know how to set a " + field.getType().getName()); } assertFalse( "Instances with o1 having " + field.getName() + " set and o2 having it not set are equal", o1.equals(o2)); field.set(o2, field.get(o1)); assertTrue( "After setting o2 with the value of the object in o1, the two objects in the field are not equal", field.get(o1).equals(field.get(o2))); assertTrue( "Instances with o1 having " + field.getName() + " set and o2 having it set to the same object of type " + field.get(o2).getClass().getName() + " are not equal", o1.equals(o2)); if (field.getType() == String.class) { field.set(o2, TEST_STRING_VAL2); } else if (field.getType() == boolean.class) { field.setBoolean(o2, false); } else if (field.getType() == short.class) { field.setShort(o2, (short) 0); } else if (field.getType() == long.class) { field.setLong(o2, (long) 0); } else if (field.getType() == float.class) { field.setFloat(o2, (float) 0); } else if (field.getType() == int.class) { field.setInt(o2, 0); } else if (field.getType() == byte.class) { field.setByte(o2, (byte) 0); } else if (field.getType() == char.class) { field.setChar(o2, (char) 0); } else if (field.getType() == double.class) { field.setDouble(o2, (double) 1); } else if (field.getType().isEnum()) { field.set(o2, field.getType().getEnumConstants()[1]); } else if (Object.class.isAssignableFrom(field.getType())) { field.set(o2, field.getType().newInstance()); } else { fail("Don't know how to set a " + field.getType().getName()); } if (field.get(o1).equals(field.get(o2))) { // Even though we have different instances, they are equal. // Let's walk one of them // to see if we can find a field to set Field[] paramFields = field.get(o1).getClass().getDeclaredFields(); for (int j = 0; j < paramFields.length; j++) { paramFields[j].setAccessible(true); if (paramFields[j].getType() == String.class) { paramFields[j].set(field.get(o1), TEST_STRING_VAL1); } } } assertFalse( "After setting o2 with a different object than what is in o1, the two objects in the field are equal. " + "This is after an attempt to walk the fields to make them different", field.get(o1).equals(field.get(o2))); assertFalse( "Instances with o1 having " + field.getName() + " set and o2 having it set to a different object are equal", o1.equals(o2)); } } catch (InstantiationException e) { e.printStackTrace(); throw new AssertionError("Unable to construct an instance of the class under test"); } catch (IllegalAccessException e) { e.printStackTrace(); throw new AssertionError("Unable to construct an instance of the class under test"); } catch (SecurityException e) { e.printStackTrace(); throw new AssertionError("Unable to read the field from the class under test"); } catch (NoSuchFieldException e) { e.printStackTrace(); throw new AssertionError("Unable to find field in the class under test"); } }
/** * Inflate this entity using the current row from the given cursor. * * @param cursor The cursor to get object data from. * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InstantiationException */ @SuppressWarnings("unchecked") void inflate(Cursor cursor) throws ActiveRecordException { HashMap<Field, Long> entities = new HashMap<Field, Long>(); for (Field field : getColumnFields()) { try { String typeString = field.getType().getName(); String colName = CamelNotationHelper.toSQLName(field.getName()); if (typeString.equals("long")) { field.setLong(this, cursor.getLong(cursor.getColumnIndex(colName))); } else if (typeString.equals("java.lang.String")) { String val = cursor.getString(cursor.getColumnIndex(colName)); field.set(this, val.equals("null") ? null : val); } else if (typeString.equals("double")) { field.setDouble(this, cursor.getDouble(cursor.getColumnIndex(colName))); } else if (typeString.equals("boolean")) { field.setBoolean(this, cursor.getString(cursor.getColumnIndex(colName)).equals("true")); } else if (typeString.equals("[B")) { field.set(this, cursor.getBlob(cursor.getColumnIndex(colName))); } else if (typeString.equals("int")) { field.setInt(this, cursor.getInt(cursor.getColumnIndex(colName))); } else if (typeString.equals("float")) { field.setFloat(this, cursor.getFloat(cursor.getColumnIndex(colName))); } else if (typeString.equals("short")) { field.setShort(this, cursor.getShort(cursor.getColumnIndex(colName))); } else if (typeString.equals("java.sql.Timestamp")) { long l = cursor.getLong(cursor.getColumnIndex(colName)); field.set(this, new Timestamp(l)); } else if (field.getType().getSuperclass() == ActiveRecordBase.class) { long id = cursor.getLong(cursor.getColumnIndex(colName)); if (id > 0) entities.put(field, id); else field.set(this, null); } else if (field.getType() == List.class) { String classKey = field.getName(); // hack classKey = classKey.replaceFirst( "" + classKey.charAt(0), "" + Character.toUpperCase(classKey.charAt(0))); if (field.getName().endsWith("s")) { classKey = classKey.substring(0, classKey.length() - 1); } DatabaseBuilder ownBuilder = getDatabase().getOwnBuilder(); Class fieldClass = ownBuilder.getClassForName(classKey); if (fieldClass != null) { List<ActiveRecordBase> ownObjects = (List<ActiveRecordBase>) findByColumn( fieldClass, CamelNotationHelper.toSQLName(getTableName()), Long.toString(getID())); field.set(this, ownObjects); } } else if (field.getAnnotation(ActiveRecordIgnoreAttribute.class) != null) { continue; } else throw new ActiveRecordException( field.getName() + " of type " + field.getType() + " cannot be read from Sqlite3 database."); } catch (IllegalArgumentException e) { throw new ActiveRecordException(e.getLocalizedMessage()); } catch (IllegalAccessException e) { throw new ActiveRecordException(e.getLocalizedMessage()); } } s_EntitiesMap.set(this); for (Field f : entities.keySet()) { try { f.set( this, this.findByID((Class<? extends ActiveRecordBase>) f.getType(), entities.get(f))); } catch (SQLiteException e) { throw new ActiveRecordException(e.getLocalizedMessage()); } catch (IllegalArgumentException e) { throw new ActiveRecordException(e.getLocalizedMessage()); } catch (IllegalAccessException e) { throw new ActiveRecordException(e.getLocalizedMessage()); } } }