List of usage examples for java.lang.reflect Field setByte
@CallerSensitive @ForceInline public void setByte(Object obj, byte b) throws IllegalArgumentException, IllegalAccessException
From source file:org.sonar.api.checks.AnnotationCheckFactory.java
private void configureField(Object check, Field field, String value) { try {/*from w ww . j av a2 s. c om*/ 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); } }
From source file:org.sonar.api.checks.checkers.AnnotationCheckerFactory.java
private void configureField(Object checker, Field field, Map.Entry<String, String> parameter) throws IllegalAccessException { field.setAccessible(true);/*from w w w.ja v a2s. c om*/ if (field.getType().equals(String.class)) { field.set(checker, parameter.getValue()); } else if (field.getType().getSimpleName().equals("int")) { field.setInt(checker, Integer.parseInt(parameter.getValue())); } else if (field.getType().getSimpleName().equals("short")) { field.setShort(checker, Short.parseShort(parameter.getValue())); } else if (field.getType().getSimpleName().equals("long")) { field.setLong(checker, Long.parseLong(parameter.getValue())); } else if (field.getType().getSimpleName().equals("double")) { field.setDouble(checker, Double.parseDouble(parameter.getValue())); } else if (field.getType().getSimpleName().equals("boolean")) { field.setBoolean(checker, Boolean.parseBoolean(parameter.getValue())); } else if (field.getType().getSimpleName().equals("byte")) { field.setByte(checker, Byte.parseByte(parameter.getValue())); } else if (field.getType().equals(Integer.class)) { field.set(checker, new Integer(Integer.parseInt(parameter.getValue()))); } else if (field.getType().equals(Long.class)) { field.set(checker, new Long(Long.parseLong(parameter.getValue()))); } else if (field.getType().equals(Double.class)) { field.set(checker, new Double(Double.parseDouble(parameter.getValue()))); } else if (field.getType().equals(Boolean.class)) { field.set(checker, Boolean.valueOf(Boolean.parseBoolean(parameter.getValue()))); } else { throw new UnvalidCheckerException( "The type of the field " + field + " is not supported: " + field.getType()); } }
From source file:com.nonninz.robomodel.RoboModel.java
private void loadField(Field field, Cursor query) throws DatabaseNotUpToDateException { final Class<?> type = field.getType(); final boolean wasAccessible = field.isAccessible(); final int columnIndex = query.getColumnIndex(field.getName()); field.setAccessible(true);/*from ww w .ja va 2 s .co m*/ /* * TODO: There is the potential of a problem here: * What happens if the developer changes the type of a field between releases? * * If he saves first, then the column type will be changed (In the future). * If he loads first, we don't know if an Exception will be thrown if the * types are incompatible, because it's undocumented in the Cursor documentation. */ try { if (type == String.class) { field.set(this, query.getString(columnIndex)); } else if (type == Boolean.TYPE) { final boolean value = query.getInt(columnIndex) == 1 ? true : false; field.setBoolean(this, value); } else if (type == Byte.TYPE) { field.setByte(this, (byte) query.getShort(columnIndex)); } else if (type == Double.TYPE) { field.setDouble(this, query.getDouble(columnIndex)); } else if (type == Float.TYPE) { field.setFloat(this, query.getFloat(columnIndex)); } else if (type == Integer.TYPE) { field.setInt(this, query.getInt(columnIndex)); } else if (type == Long.TYPE) { field.setLong(this, query.getLong(columnIndex)); } else if (type == Short.TYPE) { field.setShort(this, query.getShort(columnIndex)); } else if (type.isEnum()) { final String string = query.getString(columnIndex); if (string != null && string.length() > 0) { final Object[] constants = type.getEnumConstants(); final Method method = type.getMethod("valueOf", Class.class, String.class); final Object value = method.invoke(constants[0], type, string); field.set(this, value); } } else { // Try to de-json it (db column must be of type text) try { final Object value = mMapper.readValue(query.getString(columnIndex), field.getType()); field.set(this, value); } catch (final Exception e) { final String msg = String.format("Type %s is not supported for field %s", type, field.getName()); Ln.w(e, msg); throw new IllegalArgumentException(msg); } } } catch (final IllegalAccessException e) { final String msg = String.format("Field %s is not accessible", type, field.getName()); throw new IllegalArgumentException(msg); } catch (final NoSuchMethodException e) { // Should not happen throw new RuntimeException(e); } catch (final InvocationTargetException e) { // Should not happen throw new RuntimeException(e); } catch (IllegalStateException e) { // This is when there is no column in db, but there is in the model throw new DatabaseNotUpToDateException(e); } finally { field.setAccessible(wasAccessible); } }
From source file:me.henrytao.observableorm.orm.ObservableModel.java
public T deserialize(Map<String, Object> map) throws IllegalAccessException { Field[] fields = getDeclaredFields(); for (Field f : fields) { if (!f.isAnnotationPresent(Column.class)) { continue; }/*from w w w . j a v a2 s. c o m*/ Column column = f.getAnnotation(Column.class); if (!column.deserialize()) { continue; } f.setAccessible(true); String name = column.name(); Object value = map.get(name); Class type = f.getType(); Deserializer deserializer = deserializerMap.get(type); if (deserializer != null) { f.set(this, deserializer.deserialize(value)); } else if (boolean.class.isAssignableFrom(type)) { f.setBoolean(this, value == null ? false : (Boolean) value); } else if (double.class.isAssignableFrom(type)) { f.setDouble(this, value == null ? 0.0 : (Double) value); } else if (float.class.isAssignableFrom(type)) { f.setFloat(this, value == null ? 0f : (Float) value); } else if (int.class.isAssignableFrom(type)) { f.setInt(this, value == null ? 0 : (int) value); } else if (short.class.isAssignableFrom(type)) { f.setShort(this, value == null ? 0 : (short) value); } else if (byte.class.isAssignableFrom(type)) { f.setByte(this, value == null ? 0 : (byte) value); } else if (String.class.isAssignableFrom(type)) { f.set(this, value); } else if (JSONObject.class.isAssignableFrom(type)) { // todo: nested object should be another model } } return (T) this; }
From source file:cern.c2mon.shared.common.datatag.address.impl.HardwareAddressImpl.java
/** * Create a HardwareAddress object from its XML representation. * * @param pElement DOM element containing the XML representation of a HardwareAddress object, as created by the * toConfigXML() method. * @throws RuntimeException if unable to instantiate the Hardware address * @see cern.c2mon.shared.common.datatag.address.HardwareAddress#toConfigXML() *//*from www .ja v a 2s .c om*/ public final synchronized HardwareAddress fromConfigXML(Element pElement) { Class hwAddressClass = null; HardwareAddressImpl hwAddress = null; try { hwAddressClass = Class.forName(pElement.getAttribute("class")); hwAddress = (HardwareAddressImpl) hwAddressClass.newInstance(); } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); throw new RuntimeException("Exception caught when instantiating a hardware address from XML", cnfe); } catch (IllegalAccessException iae) { iae.printStackTrace(); throw new RuntimeException("Exception caught when instantiating a hardware address from XML", iae); } catch (InstantiationException ie) { ie.printStackTrace(); throw new RuntimeException("Exception caught when instantiating a hardware address from XML", ie); } NodeList fields = pElement.getChildNodes(); Node fieldNode = null; int fieldsCount = fields.getLength(); String fieldName; String fieldValueString; String fieldTypeName = ""; for (int i = 0; i < fieldsCount; i++) { fieldNode = fields.item(i); if (fieldNode.getNodeType() == Node.ELEMENT_NODE) { fieldName = fieldNode.getNodeName(); if (fieldNode.getFirstChild() != null) { fieldValueString = fieldNode.getFirstChild().getNodeValue(); } else { fieldValueString = ""; } try { Field field = hwAddressClass.getDeclaredField(decodeFieldName(fieldName)); fieldTypeName = field.getType().getName(); if (fieldTypeName.equals("short")) { field.setShort(hwAddress, Short.parseShort(fieldValueString)); } else if (fieldTypeName.equals("java.lang.Short")) { field.set(hwAddress, new Integer(Integer.parseInt(fieldValueString))); } else if (fieldTypeName.equals("int")) { field.setInt(hwAddress, Integer.parseInt(fieldValueString)); } else if (fieldTypeName.equals("java.lang.Integer")) { field.set(hwAddress, new Integer(Integer.parseInt(fieldValueString))); } else if (fieldTypeName.equals("float")) { field.setFloat(hwAddress, Float.parseFloat(fieldValueString)); } else if (fieldTypeName.equals("java.lang.Float")) { field.set(hwAddress, new Float(Float.parseFloat(fieldValueString))); } else if (fieldTypeName.equals("double")) { field.setDouble(hwAddress, Double.parseDouble(fieldValueString)); } else if (fieldTypeName.equals("java.lang.Double")) { field.set(hwAddress, new Double(Double.parseDouble(fieldValueString))); } else if (fieldTypeName.equals("long")) { field.setLong(hwAddress, Long.parseLong(fieldValueString)); } else if (fieldTypeName.equals("java.lang.Long")) { field.set(hwAddress, new Long(Long.parseLong(fieldValueString))); } else if (fieldTypeName.equals("byte")) { field.setByte(hwAddress, Byte.parseByte(fieldValueString)); } else if (fieldTypeName.equals("java.lang.Byte")) { field.set(hwAddress, new Byte(Byte.parseByte(fieldValueString))); } else if (fieldTypeName.equals("char")) { field.setChar(hwAddress, fieldValueString.charAt(0)); } else if (fieldTypeName.equals("java.lang.Character")) { field.set(hwAddress, new Character(fieldValueString.charAt(0))); } else if (fieldTypeName.equals("boolean")) { field.setBoolean(hwAddress, Boolean.getBoolean(fieldValueString)); } else if (fieldTypeName.equals("java.lang.Boolean")) { field.set(hwAddress, new Boolean(Boolean.getBoolean(fieldValueString))); } else if (fieldTypeName.equals("java.util.HashMap")) { field.set(hwAddress, SimpleXMLParser.domNodeToMap(fieldNode)); } else if (field.getType().isEnum()) { Object[] enumConstants = field.getType().getEnumConstants(); for (Object enumConstant : enumConstants) { if (enumConstant.toString().equals(fieldValueString)) { field.set(hwAddress, enumConstant); } } } else { field.set(hwAddress, fieldValueString); } } catch (NoSuchFieldException nsfe) { String errorMsg = "fromConfigXML(...) - Error occured while parsing XML <HardwareAddress> tag. " + "The following variable does not exist in " + hwAddressClass.toString() + ": \"" + decodeFieldName(fieldName) + "\""; log.error(errorMsg); throw new IllegalArgumentException(errorMsg); } catch (IllegalAccessException iae) { iae.printStackTrace(); throw new RuntimeException(iae); } catch (NumberFormatException npe) { String errorMsg = "fromConfigXML(...) - Error occured while parsing XML <HardwareAddress> tag. Field \"" + fieldName + "\" shall not be empty since we expect a \"" + fieldTypeName + "\" value. Please correct the XML configuration for " + hwAddressClass.toString(); log.error(errorMsg); throw new IllegalArgumentException(errorMsg); } } } return hwAddress; }
From source file:cn.edu.zafu.corepage.base.BaseActivity.java
/** * ???//from ww w.ja va 2 s . co m * * @param savedInstanceState Bundle */ private void loadActivitySavedData(Bundle savedInstanceState) { Field[] fields = this.getClass().getDeclaredFields(); Field.setAccessible(fields, true); Annotation[] ans; for (Field f : fields) { ans = f.getDeclaredAnnotations(); for (Annotation an : ans) { if (an instanceof SaveWithActivity) { try { String fieldName = f.getName(); @SuppressWarnings("rawtypes") Class cls = f.getType(); if (cls == int.class || cls == Integer.class) { f.setInt(this, savedInstanceState.getInt(fieldName)); } else if (String.class.isAssignableFrom(cls)) { f.set(this, savedInstanceState.getString(fieldName)); } else if (Serializable.class.isAssignableFrom(cls)) { f.set(this, savedInstanceState.getSerializable(fieldName)); } else if (cls == long.class || cls == Long.class) { f.setLong(this, savedInstanceState.getLong(fieldName)); } else if (cls == short.class || cls == Short.class) { f.setShort(this, savedInstanceState.getShort(fieldName)); } else if (cls == boolean.class || cls == Boolean.class) { f.setBoolean(this, savedInstanceState.getBoolean(fieldName)); } else if (cls == byte.class || cls == Byte.class) { f.setByte(this, savedInstanceState.getByte(fieldName)); } else if (cls == char.class || cls == Character.class) { f.setChar(this, savedInstanceState.getChar(fieldName)); } else if (CharSequence.class.isAssignableFrom(cls)) { f.set(this, savedInstanceState.getCharSequence(fieldName)); } else if (cls == float.class || cls == Float.class) { f.setFloat(this, savedInstanceState.getFloat(fieldName)); } else if (cls == double.class || cls == Double.class) { f.setDouble(this, savedInstanceState.getDouble(fieldName)); } else if (String[].class.isAssignableFrom(cls)) { f.set(this, savedInstanceState.getStringArray(fieldName)); } else if (Parcelable.class.isAssignableFrom(cls)) { f.set(this, savedInstanceState.getParcelable(fieldName)); } else if (Bundle.class.isAssignableFrom(cls)) { f.set(this, savedInstanceState.getBundle(fieldName)); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } }
From source file:org.soyatec.windowsazure.table.internal.CloudTableRest.java
/** * Deserial the xml to object accord to the give model class. * * @param partitionKey/*w ww . j a va 2s .com*/ * @param rowKey * @param eTag * @param timestamp * @param values * @return Instance of the given model class. */ private ITableServiceEntity createObjectByModelClass(String partitionKey, String rowKey, String eTag, String timestamp, List<ICloudTableColumn> values) { ITableServiceEntity newInstance = instanceModel(partitionKey, rowKey, eTag, timestamp, values); if (newInstance == null) { return null; } // Copy Field if (values != null && !values.isEmpty()) { for (ICloudTableColumn column : values) { Field field = null; try { field = newInstance.getClass().getDeclaredField(column.getName()); } catch (NoSuchFieldException e) { continue; } if (field == null) { continue; } int modifier = field.getModifiers(); if (Modifier.isPrivate(modifier) && Modifier.isFinal(modifier) && Modifier.isStatic(modifier)) { if (getModelClass() != null) { Logger.debug(MessageFormat.format( "{0} class {1} is a static final field. Can not set data to it.", getModelClass().getClass(), field.getName())); } continue; } boolean accessible = field.isAccessible(); if (!accessible) { field.setAccessible(true); } ETableColumnType type = column.getType(); String value = column.getValue(); if (value == null) { continue; } else { try { if (type == null) { setStringOrObjectField(newInstance, column, field, value); } else if (type.equals(ETableColumnType.TYPE_BINARY)) { field.set(newInstance, Base64.decode(value)); } else if (type.equals(ETableColumnType.TYPE_BOOL)) { field.setBoolean(newInstance, Boolean.parseBoolean(value)); } else if (type.equals(ETableColumnType.TYPE_DATE_TIME)) { field.set(newInstance, Utilities.tryGetDateTimeFromTableEntry(value)); } else if (type.equals(ETableColumnType.TYPE_DOUBLE)) { field.setDouble(newInstance, Double.parseDouble(value)); } else if (type.equals(ETableColumnType.TYPE_GUID)) { Guid guid = new Guid(); try { Field valueField = guid.getClass().getDeclaredField("value"); boolean accessiable = valueField.isAccessible(); if (!accessible) { valueField.setAccessible(true); } valueField.set(guid, value); valueField.setAccessible(accessiable); field.set(newInstance, guid); } catch (NoSuchFieldException e) { Logger.error(e.getMessage(), e); } } else if (type.equals(ETableColumnType.TYPE_INT)) { try { field.setInt(newInstance, Integer.parseInt(value)); } catch (Exception e) { field.setByte(newInstance, Byte.parseByte(value)); } } else if (type.equals(ETableColumnType.TYPE_LONG)) { field.setLong(newInstance, Long.parseLong(value)); } else if (type.equals(ETableColumnType.TYPE_STRING)) { setStringOrObjectField(newInstance, column, field, value); } } catch (Exception e) { Logger.error( MessageFormat.format("{0} class filed {1} set failed.", getModelClass(), value), e); } } // revert aaccessible field.setAccessible(accessible); } } return newInstance; }
From source file:org.j2free.admin.ReflectionMarshaller.java
/** * /*ww w. j av a 2 s . c o m*/ * @param entity * @param parameterMap * @param controller * @return * @throws MarshallingException */ public Object marshallIn(Object entity, Map<String, String[]> parameterMap, Controller controller) throws MarshallingException { Field field; Converter converter; Method setter; String[] newValues; log.debug("Marshalling in instance of " + entity.getClass().getSimpleName()); boolean error = false, success = false, isEntity = false, isCollection = false; Class collectionType; Class fieldType; for (Map.Entry<Field, Converter> ent : instructions.entrySet()) { // reset flags error = success = isEntity = isCollection = false; field = ent.getKey(); converter = ent.getValue(); if (converter.isReadOnly()) { log.debug("Skipping read-only field " + field.getName()); continue; } newValues = parameterMap.get(field.getName()); if (newValues == null || newValues.length == 0) { log.debug("Skipping field " + field.getName() + ", no new value set."); continue; } isEntity = converter.isEntity(); isCollection = converter.isCollection(); fieldType = field.getType(); collectionType = isCollection ? converter.getType() : null; log.debug("Marshalling in field " + field.getName()); // try to get the original value try { if (!field.isAccessible()) { field.setAccessible(true); } if (field.isAccessible()) { log.debug(field.getName() + " is accessible"); if (!isEntity && !isCollection) { log.debug("!isEntity && !isCollection"); // if it's an array, it needs special treatment if (fieldType.isArray()) { log.debug(field.getName() + " is an Array"); Class arrayType = fieldType.getComponentType(); // If we can, just convert with a cast() if (arrayType.isAssignableFrom(String.class)) { log.debug(arrayType.getName() + " is assignable from String.class"); Object[] newArray = new Object[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = arrayType.cast(newValues[i]); } field.set(entity, newArray); } else { if (isInteger(fieldType)) { Integer[] newArray = new Integer[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Integer.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isFloat(fieldType)) { Float[] newArray = new Float[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Float.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isDouble(fieldType)) { Double[] newArray = new Double[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Double.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isShort(fieldType)) { Short[] newArray = new Short[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Short.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isChar(fieldType)) { field.set(entity, ServletUtils.join(newValues, "").toCharArray()); } else if (isLong(fieldType)) { Long[] newArray = new Long[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Long.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isBoolean(fieldType)) { Boolean[] newArray = new Boolean[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Boolean.valueOf(newValues[i]); } field.set(entity, newArray); } else if (isByte(fieldType)) { Byte[] newArray = new Byte[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Byte.valueOf(newValues[i]); } field.set(entity, newArray); } else { throw new MarshallingException( "Don't know how to marshall an array of a non-primitive, and non-assignable type! field = " + field.getName()); } } } else { // Check out if it's assignable via a straight cast, // that could save time if (fieldType.isAssignableFrom(String.class)) { log.debug(fieldType.getName() + " is assignable from String.class"); // this might throw an exception, but we're going // to ignore it because there are other ways of // setting the value if this doesn't work. try { field.set(entity, fieldType.cast(newValues[0])); log.debug("Assigned via cast"); } catch (Exception e) { log.debug("Error setting field by cast", e); } success = true; } // if it wasn't assignable via a straight cast, try // working around it. if (!success) { if (isInteger(fieldType) && !newValues[0].equals("")) { field.setInt(entity, Integer.valueOf(newValues[0])); } else if (isFloat(fieldType) && !newValues[0].equals("")) { field.setFloat(entity, Float.valueOf(newValues[0])); } else if (isDouble(fieldType) && !newValues[0].equals("")) { field.setDouble(entity, Double.valueOf(newValues[0])); } else if (isShort(fieldType) && !newValues[0].equals("")) { field.setShort(entity, Short.valueOf(newValues[0])); } else if (isChar(fieldType)) { field.setChar(entity, newValues[0].charAt(0)); } else if (isLong(fieldType) && !newValues[0].equals("")) { field.setLong(entity, Long.valueOf(newValues[0])); } else if (isBoolean(fieldType) && !newValues[0].equals("")) { field.setBoolean(entity, Boolean.valueOf(newValues[0])); } else if (isByte(fieldType) && !newValues[0].equals("")) { field.setByte(entity, Byte.valueOf(newValues[0])); } else if (isDate(fieldType)) { if (newValues[0].equals("")) { field.set(entity, null); } else { try { field.set(entity, asDate(newValues[0])); } catch (ParseException pe) { log.warn("Error parsing date: " + newValues[0], pe); } } } else if (!newValues[0].equals("")) { log.debug("Not sure how to set " + field.getName() + " of type " + fieldType.getName() + ", attemping cast."); field.set(entity, fieldType.cast(newValues[0])); } else if (newValues[0].equals("")) { log.debug("Skipping field " + field.getName() + ", empty string value passed in."); } } } } else if (isEntity && !isCollection) { log.debug("isEntity && !isCollection"); ReflectionMarshaller innerMarshaller = ReflectionMarshaller.getForClass(fieldType); field.set(entity, controller.proxy(fieldType, innerMarshaller.asIdType(newValues[0]))); } else if (!isEntity && isCollection) { log.debug("!isEntity && isCollection"); throw new MarshallingException("Error, collections of non-entities are not yet supported."); } else if (isEntity && isCollection) { log.debug("isEntity && isCollection"); // for now, this is going to expect the parameter to be a // comma-delimited string of entity ids String[] idsString = newValues[0].toString().split(","); Collection collection = (Collection) field.get(entity); log.debug("newValues.length = " + newValues.length); log.debug("newValues[0] = " + newValues[0]); log.debug("idsString.length = " + idsString.length); if (collection == null) collection = new LinkedList(); collection.clear(); if (idsString.length > 0) { ReflectionMarshaller collectionMarshaller = ReflectionMarshaller .getForClass(collectionType); log.debug("CollectionType = " + collectionType.getName()); for (String idString : idsString) { if (idString.equals("")) { log.debug("Skipping empty idString"); continue; } collection.add( controller.proxy(collectionType, collectionMarshaller.asIdType(idString))); } } field.set(entity, collection); } } else { error = true; } } catch (IllegalAccessException iae) { log.error("Unable to set " + field.getName() + " directly.", iae); error = true; } catch (ClassCastException cce) { log.error("Error setting " + field.getName() + ".", cce); error = true; } // if we hit an error getting it directly, try via the getter if (error) { error = false; try { setter = converter.getSetter(); if (setter != null) { if (!setter.isAccessible()) { setter.setAccessible(true); } if (setter.isAccessible()) { if (!isEntity && !isCollection) { // if it's an array, it needs special treatment if (fieldType.isArray()) { log.debug(field.getName() + " is an Array"); Class arrayType = fieldType.getComponentType(); // If we can, just convert with a cast() if (arrayType.isAssignableFrom(String.class)) { log.debug(arrayType.getName() + " is assignable from String.class"); Object[] newArray = new Object[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = arrayType.cast(newValues[i]); } setter.invoke(entity, newArray); } else { if (isInteger(fieldType)) { Integer[] newArray = new Integer[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Integer.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isFloat(fieldType)) { Float[] newArray = new Float[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Float.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isDouble(fieldType)) { Double[] newArray = new Double[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Double.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isShort(fieldType)) { Short[] newArray = new Short[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Short.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isChar(fieldType)) { setter.invoke(entity, ServletUtils.join(newValues, "").toCharArray()); } else if (isLong(fieldType)) { Long[] newArray = new Long[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Long.valueOf(newValues[i]); } field.set(entity, (Object[]) newArray); } else if (isBoolean(fieldType)) { Boolean[] newArray = new Boolean[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Boolean.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else if (isByte(fieldType)) { Byte[] newArray = new Byte[newValues.length]; for (int i = 0; i < newValues.length; i++) { newArray[i] = Byte.valueOf(newValues[i]); } setter.invoke(entity, (Object[]) newArray); } else { throw new MarshallingException( "Don't know how to marshall an array of a non-primitive, and non-assignable type! field = " + field.getName()); } } } else { // Check out if it's assignable via a straight cast, // that could save time if (fieldType.isAssignableFrom(String.class)) { log.debug(fieldType.getName() + " is assignable from String.class"); // this might throw an exception, but we're going // to ignore it because there are other ways of // setting the value if this doesn't work. try { setter.invoke(entity, fieldType.cast(newValues[0])); } catch (Exception e) { log.debug("Error setting field by cast", e); } success = true; } // if it wasn't assignable via a straight cast, try // working around it. if (!success) { if (isInteger(fieldType)) { setter.invoke(entity, Integer.valueOf(newValues[0])); } else if (isFloat(fieldType)) { setter.invoke(entity, Float.valueOf(newValues[0])); } else if (isDouble(fieldType)) { setter.invoke(entity, Double.valueOf(newValues[0])); } else if (isShort(fieldType)) { setter.invoke(entity, Short.valueOf(newValues[0])); } else if (isChar(fieldType)) { setter.invoke(entity, newValues[0].charAt(0)); } else if (isLong(fieldType)) { setter.invoke(entity, Long.valueOf(newValues[0])); } else if (isBoolean(fieldType)) { setter.invoke(entity, Boolean.valueOf(newValues[0])); } else if (isByte(fieldType)) { setter.invoke(entity, Byte.valueOf(newValues[0])); } else if (isDate(fieldType)) { if (newValues[0].equals("")) { field.set(entity, null); } else { try { setter.invoke(entity, asDate(newValues[0])); } catch (ParseException pe) { log.warn("Error parsing date: " + newValues[0], pe); } } } else { log.debug("Not sure how to set " + field.getName() + " of type " + fieldType.getName() + ", attemping cast."); setter.invoke(entity, fieldType.cast(newValues[0])); } } } } else if (isEntity && !isCollection) { ReflectionMarshaller innerMarshaller = ReflectionMarshaller.getForClass(fieldType); setter.invoke(entity, controller.proxy(fieldType, innerMarshaller.asIdType(newValues[0]))); } else if (!isEntity && isCollection) { throw new MarshallingException( "Error, collections of non-entities are not yet supported."); } else if (isEntity && isCollection) { // for now, this is going to expect the parameter to be a // comma-delimited string of entity ids String[] idsString = newValues[0].toString().split(","); Collection collection = (Collection) field.get(entity); if (collection == null) collection = new LinkedList(); if (idsString.length == 0 && collection.isEmpty()) continue; collection.clear(); if (idsString.length > 0) { ReflectionMarshaller collectionMarshaller = ReflectionMarshaller .getForClass(collectionType); for (String idString : idsString) { if (idString.equals("")) { log.debug("Skipping empty idString"); continue; } collection.add(controller.proxy(collectionType, collectionMarshaller.asIdType(idString))); } } setter.invoke(entity, collection); } } else { error = true; } } else { error = true; } } catch (IllegalAccessException iae) { log.error("Error accessing setter", iae); error = true; } catch (InvocationTargetException ite) { log.error("Error invoking setter", ite); error = true; } } if (error) { throw new MarshallingException("Unable to marshall in field " + field.getName() + "."); } } return entity; }