/** * 把查询结果填充到vo中 * * @param rs 查询结果,由调用负责游标 * @param t vo * @throws IllegalArgumentException * @throws IllegalAccessException * @throws SQLException */ private void fillVO(ResultSet rs, T t) throws IllegalArgumentException, IllegalAccessException, SQLException { for (Field f : listTableFields(t.getClass())) { String name = findFieldName(f); Object object = rs.getObject(name); if (object != null) { if (!f.isAccessible()) { f.setAccessible(true); } if (isBoolean(f)) { f.setBoolean(t, rs.getBoolean(name)); } else if (isInt(f)) { f.setInt(t, rs.getInt(name)); } else if (isLong(f)) { f.setLong(t, rs.getLong(name)); } else if (isString(f)) { f.set(t, rs.getString(name)); } else if (isDate(f)) { f.set(t, rs.getTimestamp(name)); } else if (isByte(f)) { f.setByte(t, rs.getByte(name)); } else if (isChar(f)) { f.setChar(t, rs.getString(name).charAt(0)); } else if (isDouble(f)) { f.setDouble(t, rs.getDouble(name)); } else if (isFloat(f)) { f.setFloat(t, rs.getFloat(name)); } else { f.set(t, object); } } } }
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; }
private Object setField(ResultSet rs, Object info) { Field[] fields = info.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); String name = field.getName(); String type = field.getType().getName(); try { if (type.equals(String.class.getName())) { field.set(info, rs.getString(name)); } else if (type.equals(int.class.getName())) { field.setInt(info, rs.getInt(name)); } else if (type.equals(Date.class.getName())) { field.set(info, new java.util.Date(rs.getTimestamp(name).getTime())); } else if (type.equals(long.class.getName())) { field.setLong(info, rs.getLong(name)); } else if (type.equals(char.class.getName())) { String sampleType = rs.getString(name); if (sampleType != null && sampleType.length() > 0) field.setChar(info, sampleType.charAt(0)); } else { field.set(info, rs.getObject(name)); } /*} catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace();*/ } catch (Exception e) { } field.setAccessible(false); } return info; }
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()); } }
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); } }
/** * 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 } }
public void deserialize(JsonObject jo, Object t, Field field) throws IllegalAccessException { if (jo.has(field.getName())) { Long l = jo.getAsJsonPrimitive(field.getName()).getAsLong(); field.setLong(t, l); } }
void deserialize(AbstractHessianInput in, Object obj) throws IOException { long value = 0; try { value = in.readLong(); _field.setLong(obj, value); } catch (Exception e) { logDeserializeError(_field, obj, value, e); } }
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); } }
private void initializeClass(Object originalObject) { Class originalClass = originalObject.getClass(); long index = 0L; for (Field field : originalClass.getDeclaredFields()) { if (field.isAnnotationPresent(ReferenceCopy.class)) { continue; } try { if (field.getType().equals(String.class)) { field.setAccessible(true); field.set(originalObject, "Test" + index); } if (field.getType().equals(long.class)) { field.setAccessible(true); field.setLong(originalObject, index); } if (field.getType().equals(int.class)) { field.setAccessible(true); field.setInt(originalObject, (int) index); } if (field.getType().equals(List.class)) { field.setAccessible(true); ParameterizedType myListType = ((ParameterizedType) field.getGenericType()); // myListType.getActualTypeArguments()[0].name; // string value that looks like this: // interface org.kuali.rice.krad.uif.component.Component int something = 2; // Class listClass = Class.forName(myListType.getActualTypeArguments()[0]); Object[] objects = new Object[1]; objects[0] = new FieldBase(); List<?> fieldList = Arrays.asList((Object[]) objects); field.set(originalObject, fieldList); List<?> retrievedList = (List<?>) field.get(originalObject); int somethingElse = 3; // ArrayList<?> arrayList = new ArrayList<?>(); } } catch (IllegalAccessException e) { // do nothing } ++index; } }
/** * 数据格式转化 * * @param cursor * @return * @throws InstantiationException * @throws IllegalAccessException */ private T parseFromCursor(Cursor cursor) throws InstantiationException, IllegalAccessException { T t = mClazz.newInstance(); Field[] fields = mClazz.getDeclaredFields(); for (Field field : fields) { Column column = field.getAnnotation(Column.class); if (column == null) { continue; } if (column.type() == DataType.INT) { int value = cursor.getInt(cursor.getColumnIndex(column.name())); field.setInt(t, value); } else if (column.type() == DataType.LONG) { long value = cursor.getLong((cursor.getColumnIndex(column.name()))); field.setLong(t, value); } else if (column.type() == DataType.TEXT) { String value = cursor.getString(cursor.getColumnIndex(column.name())); field.set(t, value); } } return t; }
/** * 设置对象的指定属性值 * * @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)); } }
private void setValueToModel(String preferenceName, T model, Field field) { field.setAccessible(true); try { if (field.getType().equals(boolean.class)) { boolean booleanValue = mSharedPreferences.getBoolean(preferenceName, false); field.setBoolean(model, booleanValue); return; } if (field.getType().equals(int.class)) { int integerValue = mSharedPreferences.getInt(preferenceName, 0); field.setInt(model, integerValue); return; } if (field.getType().equals(float.class)) { float floatValue = mSharedPreferences.getFloat(preferenceName, 0f); field.setFloat(model, floatValue); return; } if (field.getType().equals(long.class)) { long longValue = mSharedPreferences.getLong(preferenceName, 0L); field.setLong(model, longValue); return; } if (field.getType().equals(String.class)) { String stringValue = mSharedPreferences.getString(preferenceName, EMPTY_STRING); field.set(model, stringValue); return; } Gson gson = new Gson(); String stringValue = mSharedPreferences.getString(preferenceName, EMPTY_STRING); field.set(model, gson.fromJson(stringValue, field.getDeclaringClass())); } catch (IllegalAccessException e) { Log.wtf(TAG, "Exception during converting of Preference to Field's value", e); } }
void setLong(Object obj, long l) throws IllegalArgumentException, IllegalAccessException { javaField.setLong(obj, l); }
@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; }
/** * Parses a text string to set variables dynamically at run time. * * @param _parse * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalAccessException * @throws IOException */ private void read(String _parse) throws SecurityException, NoSuchFieldException, IllegalAccessException, IOException { StringTokenizer stk = new StringTokenizer(_parse); tk = stk.nextToken(); // Try to retrieve a Field by the name provided as a token. If it is // unavailable then return back to the while. Field f = this.getClass().getField(tk); Type t = f.getType(); // If the identified field is of type int: if (t.toString().equalsIgnoreCase("int")) { Integer i = Integer.parseInt(stk.nextToken()); f.setInt(this, i); parse = br.readLine(); } // If the identified field is of type long: else if (t.toString().equalsIgnoreCase("long")) { Long l = Long.parseLong(stk.nextToken()); f.setLong(this, l); parse = br.readLine(); } // If the identified field is of type double: else if (t.toString().equalsIgnoreCase("double")) { f.setDouble(this, Double.parseDouble(stk.nextToken())); parse = br.readLine(); } // If the identified field is of type boolean: else if (t.toString().equalsIgnoreCase("boolean")) { String ntk = stk.nextToken(); if (!ntk.equalsIgnoreCase("true") && !ntk.equalsIgnoreCase("false")) { System.out.println( "Invalid parameter value provided for variable " + f.getName() + ", setting to false"); } f.setBoolean(this, Boolean.valueOf(ntk)); parse = br.readLine(); } // If the identified field is of type int[]: else if (t.toString().equalsIgnoreCase("class [I")) { int[] ia = new int[stk.countTokens()]; int i = 0; while (stk.hasMoreTokens()) { ia[i] = Integer.parseInt(stk.nextToken()); i++; } f.set(this, ia); parse = br.readLine(); } // If the identified field is of type double[]: else if (t.toString().equalsIgnoreCase("class [F")) { float[] fa = new float[stk.countTokens()]; int i = 0; while (stk.hasMoreTokens()) { fa[i] = Integer.parseInt(stk.nextToken()); i++; } f.set(this, fa); parse = br.readLine(); } // If the identified field is of type double[]: else if (t.toString().equalsIgnoreCase("class [D")) { double[] da = new double[stk.countTokens()]; int i = 0; while (stk.hasMoreTokens()) { da[i] = Integer.parseInt(stk.nextToken()); i++; } f.set(this, da); parse = br.readLine(); } // If the identified field is of type String: else if (t.toString().equalsIgnoreCase("class java.lang.String")) { f.set(this, stk.nextToken()); parse = br.readLine(); } // If the identified field is of type Date: else if (t.toString().equalsIgnoreCase("class java.util.Date")) { // Appropriate filtering needs to be added here; try { SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy_HH:mm:ss", Locale.US); sdf.setCalendar(Calendar.getInstance()); Date d = sdf.parse(stk.nextToken()); f.set(this, d); } catch (IllegalAccessException ex2) { ex2.printStackTrace(); } catch (IllegalArgumentException ex2) { ex2.printStackTrace(); } catch (ParseException ex2) { ex2.printStackTrace(); } parse = br.readLine(); } else if (t.toString().equalsIgnoreCase("class java.io.File")) { File iFile = new File(stk.nextToken()); f.set(this, iFile); parse = br.readLine(); } // If the type is none of the above, conversion hasn't been // implemented therefore ignore and continue. else { System.out.println("Type " + t.toString() + " cannot be converted. Continuing..."); parse = br.readLine(); } }
/** * 从文件读取属性值 * * @param reader 读取器 * @param field 要读取的属性 * @param obj 目标对象 * @param pre key前缀 */ private void push(SharedPreferences reader, Field field, Object obj, String pre) { // 关闭属性访问权限检查 field.setAccessible(true); try { Log.v(LOG_TAG + "push", "field type is " + field.getType().getName()); Log.v(LOG_TAG + "push", "field name is " + field.getName()); // 是否需要解密 if (cipher != null && field.isAnnotationPresent(Encrypt.class)) { Log.v(LOG_TAG + "push", "field " + field.getName() + " need decrypt"); String cipherText = reader.getString(pre + "." + field.getName(), (String) field.get(obj)); if (cipherText != null) { String data = cipher.decrypt(cipherText); // 根据属性类型选择操作 switch (field.getType().getName()) { case "java.lang.String": field.set(obj, data); break; case "int": field.setInt(obj, Integer.parseInt(data)); break; case "boolean": field.setBoolean(obj, Boolean.parseBoolean(data)); break; case "float": field.setFloat(obj, Float.parseFloat(data)); break; case "long": field.setLong(obj, Long.parseLong(data)); break; } } return; } // 根据属性类型选择操作 switch (field.getType().getName()) { case "java.lang.String": field.set(obj, reader.getString(pre + "." + field.getName(), (String) field.get(obj))); break; case "int": field.setInt(obj, reader.getInt(pre + "." + field.getName(), field.getInt(obj))); break; case "boolean": field.setBoolean( obj, reader.getBoolean(pre + "." + field.getName(), field.getBoolean(obj))); break; case "float": field.setFloat(obj, reader.getFloat(pre + "." + field.getName(), field.getFloat(obj))); break; case "long": field.setLong(obj, reader.getLong(pre + "." + field.getName(), field.getLong(obj))); break; } Log.v(LOG_TAG + "push", "field value is " + field.get(obj)); } catch (IllegalAccessException e) { Log.d(LOG_TAG + "push", "IllegalAccessException is " + e.getMessage()); } }
/** * Tries to store a key=value pair into the class or object's field. * * @param seckey Section and key in one string. This have to be pre-parsed to confirm with the * naming convention of the config class. * @param value Value string to be stored. * @param into Class to store into. * @param object Object to store into if there is non-static fields. * @throws IllegalArgumentException If there is a parsing or storing problem. */ private static synchronized void storeKeyValue( String seckey, String value, Class<?> into, Object object) throws IllegalArgumentException { // long_key consists of section name/key name ... Field field = null; Class<?> type = null; String tmp; try { field = into.getDeclaredField(seckey); type = field.getType(); if (type.isEnum()) { tmp = value.replaceAll("-", "_"); // - is invalid enum stuff... replace with _. field.set(object, Enum.valueOf((Class<? extends Enum>) type, tmp)); } else if (type.isAssignableFrom(Integer.TYPE)) field.setInt(object, Integer.parseInt(value)); else if (type.isAssignableFrom(Long.TYPE)) field.setLong(object, Long.parseLong(value)); else if (type.isAssignableFrom(Float.TYPE)) field.setFloat(object, Float.parseFloat(value)); else if (type.isAssignableFrom(Double.TYPE)) field.setDouble(object, Double.parseDouble(value)); else if (type.isAssignableFrom(Byte.TYPE)) field.setByte(object, Byte.parseByte(value)); else if (type.isAssignableFrom(String.class)) field.set(object, value); else if (type.isAssignableFrom(Character.TYPE)) { tmp = value; if (tmp.length() == 2) { tmp = tmp.replaceAll("\\t", "\t"); tmp = tmp.replaceAll("\\n", "\n"); tmp = tmp.replaceAll("\\r", "\r"); tmp = tmp.replaceAll("\\\"", "\""); tmp = tmp.replaceAll("\\\'", "\'"); } if (tmp.length() != 1) throw new NumberFormatException(); field.setChar(object, tmp.charAt(0)); } else if (type.isAssignableFrom(Boolean.TYPE)) { tmp = value.toLowerCase(); tmp = tmp.replace("yes", "true"); tmp = tmp.replace("on", "true"); tmp = tmp.replace("1", "true"); field.setBoolean(object, Boolean.valueOf(tmp)); } else { // "unknown" type, lets try a default from String constructor. field.set(object, type.getConstructor(String.class).newInstance(value)); } } catch (SecurityException e) { throw new IllegalArgumentException( "unsupported option " + into.getName() + "." + seckey + ", security protected"); } catch (NoSuchFieldException e) { throw new IllegalArgumentException( "unsupported option " + into.getName() + "." + seckey + ", no such field"); /**/ } catch (NumberFormatException e) { throw new IllegalArgumentException( "illegal number format on " + into.getName() + "." + seckey + ", " + value + " is not " + (type.isAssignableFrom(Integer.TYPE) ? "an " : "a ") + type.getName()); /**/ } catch (IllegalArgumentException e) { // System.err.println("IllegalArgumentException "+e.getMessage()); if (e.getMessage().startsWith("No enum")) { throw new IllegalArgumentException( "unsupported enum value on field " + into.getName() + ", value \"" + value + "\" not valid"); } throw new IllegalArgumentException( "unsupported option field " + into.getName() + "." + seckey + ", illegal argument when setting value"); /**/ } catch (IllegalAccessException e) { throw new IllegalArgumentException( "unsupported option field " + into.getName() + "." + seckey + ", access denied"); /**/ } catch (NoSuchMethodException e) { throw new IllegalArgumentException( "unsupported field type " + field.getClass().getName() + ", no suitable constructor"); /**/ } catch (InstantiationException e) { throw new IllegalArgumentException( "unsupported field type " + field.getClass().getName() + ", instantiation error"); /**/ } catch (InvocationTargetException e) { throw new IllegalArgumentException( "unsupported field type " + field.getClass().getName() + ", unable to invocate constructor"); /**/ } catch (EnumConstantNotPresentException e) { System.err.println("EnumConstantNotPresentException " + e.getMessage()); throw new IllegalArgumentException( "unsupported enum value on field " + into.getName() + ", constant \"" + value + "\" not present"); } catch (Exception e) { throw new IllegalArgumentException( "unsupported field type " + field.getClass().getName() + ", unknown error in setting value"); /**/ } }
@SuppressWarnings("unchecked") /** Given a set of properties, load this into the current SqoopOptions instance. */ public void loadProperties(Properties props) { try { Field[] fields = getClass().getDeclaredFields(); for (Field f : fields) { if (f.isAnnotationPresent(StoredAsProperty.class)) { Class typ = f.getType(); StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class); String propName = storedAs.value(); if (typ.equals(int.class)) { f.setInt(this, getIntProperty(props, propName, f.getInt(this))); } else if (typ.equals(boolean.class)) { f.setBoolean(this, getBooleanProperty(props, propName, f.getBoolean(this))); } else if (typ.equals(long.class)) { f.setLong(this, getLongProperty(props, propName, f.getLong(this))); } else if (typ.equals(String.class)) { f.set(this, props.getProperty(propName, (String) f.get(this))); } else if (typ.isEnum()) { f.set(this, Enum.valueOf(typ, props.getProperty(propName, f.get(this).toString()))); } else { throw new RuntimeException( "Could not retrieve property " + propName + " for type: " + typ); } } } } catch (IllegalAccessException iae) { throw new RuntimeException("Illegal access to field in property setter", iae); } // Now load properties that were stored with special types, or require // additional logic to set. if (getBooleanProperty(props, "db.require.password", false)) { // The user's password was stripped out from the metastore. // Require that the user enter it now. setPasswordFromConsole(); } else { this.password = props.getProperty("db.password", this.password); } if (this.jarDirIsAuto) { // We memoized a user-specific nonce dir for compilation to the data // store. Disregard that setting and create a new nonce dir. String localUsername = System.getProperty("user.name", "unknown"); this.jarOutputDir = getNonceJarDir(tmpDir + "sqoop-" + localUsername + "/compile"); } String colListStr = props.getProperty("db.column.list", null); if (null != colListStr) { this.columns = listToArray(colListStr); } this.inputDelimiters = getDelimiterProperties(props, "codegen.input.delimiters", this.inputDelimiters); this.outputDelimiters = getDelimiterProperties(props, "codegen.output.delimiters", this.outputDelimiters); this.extraArgs = getArgArrayProperty(props, "tool.arguments", this.extraArgs); // Delimiters were previously memoized; don't let the tool override // them with defaults. this.areDelimsManuallySet = true; }
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()); } } }