List of usage examples for java.lang.reflect Array set
public static native void set(Object array, int index, Object value) throws IllegalArgumentException, ArrayIndexOutOfBoundsException;
From source file:org.nextframework.controller.ExtendedBeanWrapper.java
protected void setPropertyValue(PropertyTokenHolder tokens, Object newValue) throws BeansException { String propertyName = tokens.canonicalName; if (tokens.keys != null) { // apply indexes and map keys: fetch value for all keys but the last one PropertyTokenHolder getterTokens = new PropertyTokenHolder(); getterTokens.canonicalName = tokens.canonicalName; getterTokens.actualName = tokens.actualName; getterTokens.keys = new String[tokens.keys.length - 1]; System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1); Object propValue = null;// ww w .ja va 2 s . c om Type type; try { propValue = getPropertyValue(getterTokens); type = getPropertyType(getterTokens); if (propValue == null) { Class rawType = null; if (type instanceof ParameterizedType) { if (((ParameterizedType) type).getRawType() instanceof Class) { rawType = (Class) ((ParameterizedType) type).getRawType(); } else if (type instanceof Class) { rawType = (Class) type; } } if (rawType != null && List.class.isAssignableFrom(rawType)) { PropertyTokenHolder propertyTokenHolder = new PropertyTokenHolder(); propertyTokenHolder.actualName = getterTokens.actualName; propertyTokenHolder.canonicalName = getterTokens.canonicalName; setPropertyValue(propertyTokenHolder, new ArrayList()); } } } catch (NotReadablePropertyException ex) { throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value in property referenced " + "in indexed property path '" + propertyName + "'", ex); } // set value for last key String key = tokens.keys[tokens.keys.length - 1]; if (propValue == null) { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value in property referenced " + "in indexed property path '" + propertyName + "': returned null"); } else if (propValue.getClass().isArray()) { Class requiredType = propValue.getClass().getComponentType(); int arrayIndex = Integer.parseInt(key); Object oldValue = null; try { if (this.extractOldValueForEditor) { oldValue = Array.get(propValue, arrayIndex); } Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue, requiredType); Array.set(propValue, Integer.parseInt(key), convertedValue); } catch (IllegalArgumentException ex) { PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, newValue); throw new TypeMismatchException(pce, requiredType, ex); } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid array index in property path '" + propertyName + "'", ex); } } else if (propValue instanceof List) { List list = (List) propValue; int index = Integer.parseInt(key); Object oldValue = null; if (this.extractOldValueForEditor && index < list.size()) { oldValue = list.get(index); } Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue, null); if (index < list.size()) { list.set(index, convertedValue); } else if (index >= list.size()) { for (int i = list.size(); i < index; i++) { try { list.add(null); } catch (NullPointerException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot set element with index " + index + " in List of size " + list.size() + ", accessed using property path '" + propertyName + "': List does not support filling up gaps with null elements"); } } list.add(convertedValue); } } else if (propValue instanceof Map) { Map map = (Map) propValue; propValue.getClass().getGenericSuperclass(); Object oldValue = null; if (this.extractOldValueForEditor) { oldValue = map.get(key); } Type type2 = ((ParameterizedType) type).getActualTypeArguments()[1]; Type type3 = ((ParameterizedType) type).getActualTypeArguments()[0]; Class reqClass = null; Class keyReqClass = null; if (type2 instanceof Class) { reqClass = (Class) type2; } else if (type2 instanceof ParameterizedType) { reqClass = (Class) ((ParameterizedType) type2).getRawType(); } if (type3 instanceof Class) { keyReqClass = (Class) type3; } else if (type3 instanceof ParameterizedType) { keyReqClass = (Class) ((ParameterizedType) type3).getRawType(); } Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue, reqClass); Object convertedKey = doTypeConversionIfNecessary(key, keyReqClass); map.put(convertedKey, convertedValue); } else { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Property referenced in indexed property path '" + propertyName + "' is neither an array nor a List nor a Map; returned value was [" + newValue + "]"); } } else { PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName); if (pd == null || pd.getWriteMethod() == null) { throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName); } Method readMethod = pd.getReadMethod(); Method writeMethod = pd.getWriteMethod(); Object oldValue = null; if (this.extractOldValueForEditor && readMethod != null) { try { oldValue = readMethod.invoke(this.object, new Object[0]); } catch (Exception ex) { logger.debug("Could not read previous value of property '" + this.nestedPath + propertyName, ex); } } try { Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue, pd.getPropertyType()); if (pd.getPropertyType().isPrimitive() && (convertedValue == null || "".equals(convertedValue))) { throw new IllegalArgumentException("Invalid value [" + newValue + "] for property '" + pd.getName() + "' of primitive type [" + pd.getPropertyType() + "]"); } if (logger.isDebugEnabled()) { logger.debug("About to invoke write method [" + writeMethod + "] on object of class [" + this.object.getClass().getName() + "]"); } writeMethod.invoke(this.object, new Object[] { convertedValue }); if (logger.isDebugEnabled()) { logger.debug("Invoked write method [" + writeMethod + "] with value of type [" + pd.getPropertyType().getName() + "]"); } } catch (InvocationTargetException ex) { PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, newValue); if (ex.getTargetException() instanceof ClassCastException) { throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException()); } else { throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException()); } } catch (IllegalArgumentException ex) { PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, newValue); throw new TypeMismatchException(pce, pd.getPropertyType(), ex); } catch (IllegalAccessException ex) { PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, newValue); throw new MethodInvocationException(pce, ex); } } }
From source file:org.apache.axis2.jaxws.marshaller.impl.alt.DocLitWrappedMinimalMethodMarshaller.java
/** * Add component to the container object * @param container array or List/*from w ww. j a v a 2 s . c o m*/ * @param component * @param index * @param container */ private static void addComponent(Object container, Object component, int index) { if (container.getClass().isArray()) { if (component != null) { Array.set(container, index, component); } } else { ((List) container).add(component); } }
From source file:org.forgerock.openidm.provisioner.openicf.impl.OpenICFProvisionerService.java
private Promise<ActionResponse, ResourceException> handleScriptAction(final ActionRequest request) { try {//from w ww .j a v a2 s .com final String scriptId = request.getAdditionalParameter(SystemAction.SCRIPT_ID); if (StringUtils.isBlank(scriptId)) { return new BadRequestException("Missing required parameter: " + SystemAction.SCRIPT_ID).asPromise(); } if (!localSystemActionCache.containsKey(scriptId)) { return new BadRequestException("Script ID: " + scriptId + " is not defined.").asPromise(); } SystemAction action = localSystemActionCache.get(scriptId); String systemType = connectorReference.getConnectorKey().getConnectorName(); final List<ScriptContextBuilder> scriptContextBuilderList = action.getScriptContextBuilders(systemType); if (scriptContextBuilderList.isEmpty()) { return new BadRequestException( "Script ID: " + scriptId + " for systemType " + systemType + " is not defined.") .asPromise(); } JsonValue result = new JsonValue(new HashMap<String, Object>()); boolean onConnector = !"resource" .equalsIgnoreCase(request.getAdditionalParameter(SystemAction.SCRIPT_EXECUTE_MODE)); final ConnectorFacade facade = getConnectorFacade0( onConnector ? ScriptOnConnectorApiOp.class : ScriptOnResourceApiOp.class); String variablePrefix = request.getAdditionalParameter(SystemAction.SCRIPT_VARIABLE_PREFIX); List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>( scriptContextBuilderList.size()); result.put("actions", resultList); for (ScriptContextBuilder contextBuilder : scriptContextBuilderList) { boolean isShell = contextBuilder.getScriptLanguage().equalsIgnoreCase("Shell"); for (Entry<String, String> entry : request.getAdditionalParameters().entrySet()) { final String key = entry.getKey(); if (SystemAction.SCRIPT_PARAMS.contains(key)) { continue; } Object value = entry.getValue(); Object newValue = value; if (isShell) { if ("password".equalsIgnoreCase(key)) { if (value instanceof String) { newValue = new GuardedString(((String) value).toCharArray()); } else { return new BadRequestException("Invalid type for password.").asPromise(); } } if ("username".equalsIgnoreCase(key)) { if (value instanceof String == false) { return new BadRequestException("Invalid type for username.").asPromise(); } } if ("workingdir".equalsIgnoreCase(key)) { if (value instanceof String == false) { return new BadRequestException("Invalid type for workingdir.").asPromise(); } } if ("timeout".equalsIgnoreCase(key)) { if (!(value instanceof String) && !(value instanceof Number)) { return new BadRequestException("Invalid type for timeout.").asPromise(); } } contextBuilder.addScriptArgument(key, newValue); continue; } if (null != value) { if (value instanceof Collection) { newValue = Array.newInstance(Object.class, ((Collection) value).size()); int i = 0; for (Object v : (Collection) value) { if (null == v || FrameworkUtil.isSupportedAttributeType(v.getClass())) { Array.set(newValue, i, v); } else { // Serializable may not be // acceptable Array.set(newValue, i, v instanceof Serializable ? v : v.toString()); } i++; } } else if (value.getClass().isArray()) { // TODO implement the array support later } else if (!FrameworkUtil.isSupportedAttributeType(value.getClass())) { // Serializable may not be acceptable newValue = value instanceof Serializable ? value : value.toString(); } } contextBuilder.addScriptArgument(key, newValue); } JsonValue content = request.getContent(); // if there is no content(content.isNull()), skip adding content to script arguments if (content.isMap()) { for (Entry<String, Object> entry : content.asMap().entrySet()) { contextBuilder.addScriptArgument(entry.getKey(), entry.getValue()); } } else if (!content.isNull()) { return new BadRequestException("Content is not of type Map").asPromise(); } // ScriptContext scriptContext = script.getScriptContextBuilder().build(); OperationOptionsBuilder operationOptionsBuilder = new OperationOptionsBuilder(); // It's necessary to keep the backward compatibility with Waveset IDM if (null != variablePrefix && isShell) { operationOptionsBuilder.setOption("variablePrefix", variablePrefix); } Map<String, Object> actionResult = new HashMap<String, Object>(2); try { Object scriptResult = null; if (onConnector) { scriptResult = facade.runScriptOnConnector(contextBuilder.build(), operationOptionsBuilder.build()); } else { scriptResult = facade.runScriptOnResource(contextBuilder.build(), operationOptionsBuilder.build()); } actionResult.put("result", ConnectorUtil.coercedTypeCasting(scriptResult, Object.class)); } catch (Throwable t) { logger.error("Script execution error.", t); actionResult.put("error", t.getMessage()); } resultList.add(actionResult); } return newActionResponse(result).asPromise(); } catch (ResourceException e) { return e.asPromise(); } catch (Exception e) { return new InternalServerErrorException(e.getMessage(), e).asPromise(); } }
From source file:com.mawujun.util.ObjectUtils.java
/** * <p>Clone an object.</p>//from w ww . j av a2 s . c om * * @param <T> the type of the object * @param obj the object to clone, null returns null * @return the clone if the object implements {@link Cloneable} otherwise {@code null} * @throws CloneFailedException if the object is cloneable and the clone operation fails * @since 3.0 */ public static <T> T clone(final T obj) { if (obj instanceof Cloneable) { final Object result; if (obj.getClass().isArray()) { final Class<?> componentType = obj.getClass().getComponentType(); if (!componentType.isPrimitive()) { result = ((Object[]) obj).clone(); } else { int length = Array.getLength(obj); result = Array.newInstance(componentType, length); while (length-- > 0) { Array.set(result, length, Array.get(obj, length)); } } } else { try { final Method clone = obj.getClass().getMethod("clone"); result = clone.invoke(obj); } catch (final NoSuchMethodException e) { throw new CloneFailedException( "Cloneable type " + obj.getClass().getName() + " has no clone method", e); } catch (final IllegalAccessException e) { throw new CloneFailedException("Cannot clone Cloneable type " + obj.getClass().getName(), e); } catch (final InvocationTargetException e) { throw new CloneFailedException("Exception cloning Cloneable type " + obj.getClass().getName(), e.getCause()); } } @SuppressWarnings("unchecked") final T checked = (T) result; return checked; } return null; }
From source file:org.mypsycho.beans.PropertyUtilsBean.java
/** * Set the value of the specified indexed property of the specified * bean, with no type conversions. In addition to supporting the JavaBeans * specification, this method has been extended to support <code>List</code> * objects as well.//from w w w .j a v a 2s .c o m * * @param bean Bean whose property is to be set * @param name Simple property name of the property value to be set * @param index Index of the property value to be set * @param value Value to which the indexed property element is to be set * @exception IndexOutOfBoundsException if the specified index * is outside the valid range for the underlying property * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if <code>bean</code> or * <code>name</code> is null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public void setIndexedProperty(Object bean, String name, int index, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null || name.length() == 0) { if (bean.getClass().isArray()) { Array.set(bean, index, value); return; } else if (bean instanceof List) { @SuppressWarnings("unchecked") List<Object> list = (List<Object>) bean; list.set(index, value); return; } } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } // Retrieve the property descriptor for the specified property PropertyDescriptor descriptor = getRequiredDescriptor(bean, name); invoker.set(bean, descriptor, index, value); }
From source file:org.enerj.apache.commons.beanutils.PropertyUtilsBean.java
/** * Set the value of the specified indexed property of the specified * bean, with no type conversions. In addition to supporting the JavaBeans * specification, this method has been extended to support * <code>List</code> objects as well. * * @param bean Bean whose property is to be set * @param name Simple property name of the property value to be set * @param index Index of the property value to be set * @param value Value to which the indexed property element is to be set * * @exception ArrayIndexOutOfBoundsException if the specified index * is outside the valid range for the underlying array * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if <code>bean</code> or * <code>name</code> is null * @exception InvocationTargetException if the property accessor method * throws an exception//from ww w . j ava 2 s .c o m * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public void setIndexedProperty(Object bean, String name, int index, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified"); } // Handle DynaBean instances specially if (bean instanceof DynaBean) { DynaProperty descriptor = ((DynaBean) bean).getDynaClass().getDynaProperty(name); if (descriptor == null) { throw new NoSuchMethodException("Unknown property '" + name + "'"); } ((DynaBean) bean).set(name, index, value); return; } // Retrieve the property descriptor for the specified property PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) { throw new NoSuchMethodException("Unknown property '" + name + "'"); } // Call the indexed setter method if there is one if (descriptor instanceof IndexedPropertyDescriptor) { Method writeMethod = ((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod(); if (writeMethod != null) { Object subscript[] = new Object[2]; subscript[0] = new Integer(index); subscript[1] = value; try { if (log.isTraceEnabled()) { String valueClassName = value == null ? "<null>" : value.getClass().getName(); log.trace("setSimpleProperty: Invoking method " + writeMethod + " with index=" + index + ", value=" + value + " (class " + valueClassName + ")"); } invokeMethod(writeMethod, bean, subscript); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof ArrayIndexOutOfBoundsException) { throw (ArrayIndexOutOfBoundsException) e.getTargetException(); } else { throw e; } } return; } } // Otherwise, the underlying property must be an array or a list Method readMethod = descriptor.getReadMethod(); if (readMethod == null) { throw new NoSuchMethodException("Property '" + name + "' has no getter method"); } // Call the property getter to get the array or list Object array = invokeMethod(readMethod, bean, new Object[0]); if (!array.getClass().isArray()) { if (array instanceof List) { // Modify the specified value in the List ((List) array).set(index, value); } else { throw new IllegalArgumentException("Property '" + name + "' is not indexed"); } } else { // Modify the specified value in the array Array.set(array, index, value); } }
From source file:org.eclipse.january.dataset.DatasetUtils.java
private static void setRow(Object row, Dataset a, int... pos) { final int l = Array.getLength(row); final int rank = pos.length; final int[] npos = Arrays.copyOf(pos, rank + 1); Object r;/*from w w w . jav a 2 s .c o m*/ if (rank + 1 < a.getRank()) { for (int i = 0; i < l; i++) { npos[rank] = i; r = Array.get(row, i); setRow(r, a, npos); } } else { for (int i = 0; i < l; i++) { npos[rank] = i; r = a.getObject(npos); Array.set(row, i, r); } } }
From source file:org.nextframework.controller.ExtendedBeanWrapper.java
/** * Convert the value to the required type (if necessary from a String), * for the specified property./*from w w w. ja v a 2s .c om*/ * @param propertyName name of the property * @param oldValue previous value, if available (may be <code>null</code>) * @param newValue proposed change value * @param requiredType the type we must convert to * (or <code>null</code> if not known, for example in case of a collection element) * @return the new value, possibly the result of type conversion * @throws TypeMismatchException if type conversion failed */ protected Object doTypeConversionIfNecessary(String propertyName, String fullPropertyName, Object oldValue, Object newValue, Class requiredType) throws TypeMismatchException { Object convertedValue = newValue; if (convertedValue != null) { // Custom editor for this type? PropertyEditor pe = findCustomEditor(requiredType, fullPropertyName); // Value not of required type? if (pe != null || (requiredType != null && (requiredType.isArray() || !requiredType.isAssignableFrom(convertedValue.getClass())))) { if (requiredType != null) { if (pe == null) { // No custom editor -> check BeanWrapperImpl's default editors. pe = (PropertyEditor) this.defaultEditors.get(requiredType); if (pe == null) { // No BeanWrapper default editor -> check standard JavaBean editors. pe = PropertyEditorManager.findEditor(requiredType); } } } if (pe != null && !(convertedValue instanceof String)) { // Not a String -> use PropertyEditor's setValue. // With standard PropertyEditors, this will return the very same object; // we just want to allow special PropertyEditors to override setValue // for type conversion from non-String values to the required type. try { pe.setValue(convertedValue); Object newConvertedValue = pe.getValue(); if (newConvertedValue != convertedValue) { convertedValue = newConvertedValue; // Reset PropertyEditor: It already did a proper conversion. // Don't use it again for a setAsText call. pe = null; } } catch (IllegalArgumentException ex) { throw new TypeMismatchException( createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType, ex); } } if (requiredType != null && !requiredType.isArray() && convertedValue instanceof String[]) { // Convert String array to a comma-separated String. // Only applies if no PropertyEditor converted the String array before. // The CSV String will be passed into a PropertyEditor's setAsText method, if any. if (logger.isDebugEnabled()) { logger.debug("Converting String array to comma-delimited String [" + convertedValue + "]"); } convertedValue = StringUtils.arrayToCommaDelimitedString((String[]) convertedValue); } if (pe != null && convertedValue instanceof String) { // Use PropertyEditor's setAsText in case of a String value. if (logger.isDebugEnabled()) { logger.debug( "Converting String to [" + requiredType + "] using property editor [" + pe + "]"); } try { pe.setValue(oldValue); pe.setAsText((String) convertedValue); convertedValue = pe.getValue(); } catch (IllegalArgumentException ex) { throw new TypeMismatchException( createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType, ex); } } if (requiredType != null) { // Array required -> apply appropriate conversion of elements. if (requiredType.isArray()) { Class componentType = requiredType.getComponentType(); if (convertedValue instanceof Collection) { // Convert Collection elements to array elements. Collection coll = (Collection) convertedValue; Object result = Array.newInstance(componentType, coll.size()); int i = 0; for (Iterator it = coll.iterator(); it.hasNext(); i++) { Object value = doTypeConversionIfNecessary(propertyName, propertyName + PROPERTY_KEY_PREFIX + i + PROPERTY_KEY_SUFFIX, null, it.next(), componentType); Array.set(result, i, value); } return result; } else if (convertedValue != null && convertedValue.getClass().isArray()) { // Convert Collection elements to array elements. int arrayLength = Array.getLength(convertedValue); Object result = Array.newInstance(componentType, arrayLength); for (int i = 0; i < arrayLength; i++) { Object value = doTypeConversionIfNecessary(propertyName, propertyName + PROPERTY_KEY_PREFIX + i + PROPERTY_KEY_SUFFIX, null, Array.get(convertedValue, i), componentType); Array.set(result, i, value); } return result; } else { // A plain value: convert it to an array with a single component. Object result = Array.newInstance(componentType, 1); Object value = doTypeConversionIfNecessary(propertyName, propertyName + PROPERTY_KEY_PREFIX + 0 + PROPERTY_KEY_SUFFIX, null, convertedValue, componentType); Array.set(result, 0, value); return result; } } // If the resulting value definitely doesn't match the required type, // try field lookup as fallback. If no matching field found, // throw explicit TypeMismatchException with full context information. if (convertedValue != null && !requiredType.isPrimitive() && !requiredType.isAssignableFrom(convertedValue.getClass())) { // In case of String value, try to find matching field (for JDK 1.5 // enum or custom enum with values defined as static fields). if (convertedValue instanceof String) { try { Field enumField = requiredType.getField((String) convertedValue); return enumField.get(null); } catch (Exception ex) { logger.debug("Field [" + convertedValue + "] isn't an enum value", ex); } } // Definitely doesn't match: throw TypeMismatchException. throw new TypeMismatchException( createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType); } } } } if (requiredType != null && List.class.isAssignableFrom(requiredType)) { //treat conventions of enum lists Type genericReturnType = getPropertyDescriptorInternal(fullPropertyName).getReadMethod() .getGenericReturnType(); if (genericReturnType instanceof ParameterizedType) { Type actualType = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; if (actualType instanceof Class && convertedValue != null) { List list = (List) convertedValue; for (int i = 0; i < list.size(); i++) { Object o = list.remove(i); o = doTypeConversionIfNecessary(o, (Class) actualType); list.add(i, o); } } } } return convertedValue; }
From source file:kx.c.java
/** * Sets the object at an index of an array * /*from w w w . j av a 2 s . co m*/ * @param x The array to index * @param i The offset to index at * @param y The object to set at index i */ public static void set(Object x, int i, Object y) { Array.set(x, i, null == y ? NULL[t(x)] : y); }
From source file:javadz.beanutils.PropertyUtilsBean.java
/** * Set the value of the specified indexed property of the specified * bean, with no type conversions. In addition to supporting the JavaBeans * specification, this method has been extended to support * <code>List</code> objects as well. * * @param bean Bean whose property is to be set * @param name Simple property name of the property value to be set * @param index Index of the property value to be set * @param value Value to which the indexed property element is to be set * * @exception IndexOutOfBoundsException if the specified index * is outside the valid range for the underlying property * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if <code>bean</code> or * <code>name</code> is null * @exception InvocationTargetException if the property accessor method * throws an exception/*from www . java 2 s. c om*/ * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public void setIndexedProperty(Object bean, String name, int index, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null || name.length() == 0) { if (bean.getClass().isArray()) { Array.set(bean, index, value); return; } else if (bean instanceof List) { ((List) bean).set(index, value); return; } } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } // Handle DynaBean instances specially if (bean instanceof DynaBean) { DynaProperty descriptor = ((DynaBean) bean).getDynaClass().getDynaProperty(name); if (descriptor == null) { throw new NoSuchMethodException( "Unknown property '" + name + "' on bean class '" + bean.getClass() + "'"); } ((DynaBean) bean).set(name, index, value); return; } // Retrieve the property descriptor for the specified property PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) { throw new NoSuchMethodException( "Unknown property '" + name + "' on bean class '" + bean.getClass() + "'"); } // Call the indexed setter method if there is one if (descriptor instanceof IndexedPropertyDescriptor) { Method writeMethod = ((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod(); writeMethod = MethodUtils.getAccessibleMethod(bean.getClass(), writeMethod); if (writeMethod != null) { Object[] subscript = new Object[2]; subscript[0] = new Integer(index); subscript[1] = value; try { if (log.isTraceEnabled()) { String valueClassName = value == null ? "<null>" : value.getClass().getName(); log.trace("setSimpleProperty: Invoking method " + writeMethod + " with index=" + index + ", value=" + value + " (class " + valueClassName + ")"); } invokeMethod(writeMethod, bean, subscript); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof IndexOutOfBoundsException) { throw (IndexOutOfBoundsException) e.getTargetException(); } else { throw e; } } return; } } // Otherwise, the underlying property must be an array or a list Method readMethod = getReadMethod(bean.getClass(), descriptor); if (readMethod == null) { throw new NoSuchMethodException( "Property '" + name + "' has no getter method on bean class '" + bean.getClass() + "'"); } // Call the property getter to get the array or list Object array = invokeMethod(readMethod, bean, EMPTY_OBJECT_ARRAY); if (!array.getClass().isArray()) { if (array instanceof List) { // Modify the specified value in the List ((List) array).set(index, value); } else { throw new IllegalArgumentException( "Property '" + name + "' is not indexed on bean class '" + bean.getClass() + "'"); } } else { // Modify the specified value in the array Array.set(array, index, value); } }