List of usage examples for java.lang.reflect Array get
public static native Object get(Object array, int index) throws IllegalArgumentException, ArrayIndexOutOfBoundsException;
From source file:ArrayUtils.java
/** * Replaces <code>toReplace</code> with <code>replacement</code> in * <code>array</code> one time at the most * //from w ww . j a v a 2 s . c om * @param array * The array to search and replace in * @param toReplace * The object to replace * @param replacement * The object to replace <code>toReplace</code> with the first * time it is found * @return The index where <code>toReplace</code> was found and replaced, or * -1 if it was not found in <code>array</code> */ public static int replaceOnce(Object array, Object toReplace, Object replacement) { if (array == null) return -1; if (array instanceof Object[]) { Object[] array2 = (Object[]) array; for (int i = 0; i < array2.length; i++) { if (equals(array2[i], toReplace)) { array2[i] = replacement; return i; } } return -1; } else { int i, len; len = Array.getLength(array); for (i = 0; i < len; i++) { if (equals(Array.get(array, i), toReplace)) { put(array, replacement, i); return i; } } return -1; } }
From source file:javadz.beanutils.BeanUtilsBean.java
/** * <p>Set the specified property value, performing type conversions as * required to conform to the type of the destination property.</p> * * <p>If the property is read only then the method returns * without throwing an exception.</p> * * <p>If <code>null</code> is passed into a property expecting a primitive value, * then this will be converted as if it were a <code>null</code> string.</p> * * <p><strong>WARNING</strong> - The logic of this method is customized * to meet the needs of <code>populate()</code>, and is probably not what * you want for general property copying with type conversion. For that * purpose, check out the <code>copyProperty()</code> method instead.</p> * * <p><strong>WARNING</strong> - PLEASE do not modify the behavior of this * method without consulting with the Struts developer community. There * are some subtleties to its functionality that are not documented in the * Javadoc description above, yet are vital to the way that Struts utilizes * this method.</p>// w ww. ja va 2s.c o m * * @param bean Bean on which setting is to be performed * @param name Property name (can be nested/indexed/mapped/combo) * @param value Value to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception */ public void setProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException { // Trace logging (if enabled) if (log.isTraceEnabled()) { StringBuffer sb = new StringBuffer(" setProperty("); sb.append(bean); sb.append(", "); sb.append(name); sb.append(", "); if (value == null) { sb.append("<NULL>"); } else if (value instanceof String) { sb.append((String) value); } else if (value instanceof String[]) { String[] values = (String[]) value; sb.append('['); for (int i = 0; i < values.length; i++) { if (i > 0) { sb.append(','); } sb.append(values[i]); } sb.append(']'); } else { sb.append(value.toString()); } sb.append(')'); log.trace(sb.toString()); } // Resolve any nested expression to get the actual target bean Object target = bean; Resolver resolver = getPropertyUtils().getResolver(); while (resolver.hasNested(name)) { try { target = getPropertyUtils().getProperty(target, resolver.next(name)); name = resolver.remove(name); } catch (NoSuchMethodException e) { return; // Skip this property setter } } if (log.isTraceEnabled()) { log.trace(" Target bean = " + target); log.trace(" Target name = " + name); } // Declare local variables we will require String propName = resolver.getProperty(name); // Simple name of target property Class type = null; // Java type of target property int index = resolver.getIndex(name); // Indexed subscript value (if any) String key = resolver.getKey(name); // Mapped key value (if any) // Calculate the property type if (target instanceof DynaBean) { DynaClass dynaClass = ((DynaBean) target).getDynaClass(); DynaProperty dynaProperty = dynaClass.getDynaProperty(propName); if (dynaProperty == null) { return; // Skip this property setter } type = dynaProperty.getType(); } else if (target instanceof Map) { type = Object.class; } else if (target != null && target.getClass().isArray() && index >= 0) { type = Array.get(target, index).getClass(); } else { PropertyDescriptor descriptor = null; try { descriptor = getPropertyUtils().getPropertyDescriptor(target, name); if (descriptor == null) { return; // Skip this property setter } } catch (NoSuchMethodException e) { return; // Skip this property setter } if (descriptor instanceof MappedPropertyDescriptor) { if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType(); } else if (index >= 0 && descriptor instanceof IndexedPropertyDescriptor) { if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType(); } else if (key != null) { if (descriptor.getReadMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = (value == null) ? Object.class : value.getClass(); } else { if (descriptor.getWriteMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = descriptor.getPropertyType(); } } // Convert the specified value to the required type Object newValue = null; if (type.isArray() && (index < 0)) { // Scalar value into array if (value == null) { String[] values = new String[1]; values[0] = null; newValue = getConvertUtils().convert(values, type); } else if (value instanceof String) { newValue = getConvertUtils().convert(value, type); } else if (value instanceof String[]) { newValue = getConvertUtils().convert((String[]) value, type); } else { newValue = convert(value, type); } } else if (type.isArray()) { // Indexed value into array if (value instanceof String || value == null) { newValue = getConvertUtils().convert((String) value, type.getComponentType()); } else if (value instanceof String[]) { newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType()); } else { newValue = convert(value, type.getComponentType()); } } else { // Value into scalar if (value instanceof String) { newValue = getConvertUtils().convert((String) value, type); } else if (value instanceof String[]) { newValue = getConvertUtils().convert(((String[]) value)[0], type); } else { newValue = convert(value, type); } } // Invoke the setter method try { getPropertyUtils().setProperty(target, name, newValue); } catch (NoSuchMethodException e) { throw new InvocationTargetException(e, "Cannot set " + propName); } }
From source file:ArrayUtils.java
/** * Replaces <code>toReplace</code> with <code>replacement</code> in * <code>array</code> as many times as it occurs * /*from w w w .j a v a2 s. c om*/ * @param array * The array to search and replace in * @param toReplace * The object to replace * @param replacement * The object to replace <code>toReplace</code> with each time it * is found * @return The number of times <code>toReplace</code> was found and replaced */ public static int replaceAll(Object array, Object toReplace, Object replacement) { int count = 0; if (array == null) return count; if (array instanceof Object[]) { Object[] array2 = (Object[]) array; for (int i = 0; i < array2.length; i++) { if (equals(array2[i], toReplace)) { array2[i] = replacement; count++; } } } else { int i, len; len = Array.getLength(array); for (i = 0; i < len; i++) { if (equals(Array.get(array, i), toReplace)) { put(array, replacement, i); count++; } } } return count; }
From source file:org.evergreen.web.utils.beanutils.BeanUtilsBean.java
/** * <p>Set the specified property value, performing type conversions as * required to conform to the type of the destination property.</p> * * <p>If the property is read only then the method returns * without throwing an exception.</p> * * <p>If <code>null</code> is passed into a property expecting a primitive value, * then this will be converted as if it were a <code>null</code> string.</p> * * <p><strong>WARNING</strong> - The logic of this method is customized * to meet the needs of <code>populate()</code>, and is probably not what * you want for general property copying with type conversion. For that * purpose, check out the <code>copyProperty()</code> method instead.</p> * * <p><strong>WARNING</strong> - PLEASE do not modify the behavior of this * method without consulting with the Struts developer community. There * are some subtleties to its functionality that are not documented in the * Javadoc description above, yet are vital to the way that Struts utilizes * this method.</p>/*from w w w . java 2s .c om*/ * * @param bean Bean on which setting is to be performed * @param name Property name (can be nested/indexed/mapped/combo) * @param value Value to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception */ public void setProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException { // Trace logging (if enabled) if (log.isTraceEnabled()) { StringBuffer sb = new StringBuffer(" setProperty("); sb.append(bean); sb.append(", "); sb.append(name); sb.append(", "); if (value == null) { sb.append("<NULL>"); } else if (value instanceof String) { sb.append((String) value); } else if (value instanceof String[]) { String[] values = (String[]) value; sb.append('['); for (int i = 0; i < values.length; i++) { if (i > 0) { sb.append(','); } sb.append(values[i]); } sb.append(']'); } else { sb.append(value.toString()); } sb.append(')'); log.trace(sb.toString()); } // Resolve any nested expression to get the actual target bean Object target = bean; Resolver resolver = getPropertyUtils().getResolver(); while (resolver.hasNested(name)) { try { target = getPropertyUtils().getProperty(target, resolver.next(name)); name = resolver.remove(name); } catch (NoSuchMethodException e) { return; // Skip this property setter } } if (log.isTraceEnabled()) { log.trace(" Target bean = " + target); log.trace(" Target name = " + name); } // Declare local variables we will require String propName = resolver.getProperty(name); // Simple name of target property Class type = null; // Java type of target property int index = resolver.getIndex(name); // Indexed subscript value (if any) String key = resolver.getKey(name); // Mapped key value (if any) // Calculate the property type if (target instanceof DynaBean) { DynaClass dynaClass = ((DynaBean) target).getDynaClass(); DynaProperty dynaProperty = dynaClass.getDynaProperty(propName); if (dynaProperty == null) { return; // Skip this property setter } type = dynaProperty.getType(); } else if (target instanceof Map) { type = Object.class; } else if (target != null && target.getClass().isArray() && index >= 0) { type = Array.get(target, index).getClass(); } else { PropertyDescriptor descriptor = null; try { descriptor = getPropertyUtils().getPropertyDescriptor(target, name); if (descriptor == null) { return; // Skip this property setter } } catch (NoSuchMethodException e) { return; // Skip this property setter } if (descriptor instanceof MappedPropertyDescriptor) { if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType(); } else if (index >= 0 && descriptor instanceof IndexedPropertyDescriptor) { if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType(); } else if (key != null) { if (descriptor.getReadMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = (value == null) ? Object.class : value.getClass(); } else { if (descriptor.getWriteMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = descriptor.getPropertyType(); } } // Convert the specified value to the required type Object newValue = null; if (type.isArray() && (index < 0)) { // Scalar value into array if (value == null) { String[] values = new String[1]; values[0] = null; newValue = getConvertUtils().convert(values, type); } else if (value instanceof String) { newValue = getConvertUtils().convert(value, type); } else if (value instanceof String[]) { newValue = getConvertUtils().convert((String[]) value, type); } else { newValue = convert(value, type); } } else if (type.isArray()) { // Indexed value into array if (value instanceof String || value == null) { newValue = getConvertUtils().convert((String) value, type.getComponentType()); } else if (value instanceof String[]) { newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType()); } else { newValue = convert(value, type.getComponentType()); } } else { // Value into scalar if (value instanceof String) { newValue = getConvertUtils().convert((String) value, type); } else if (value instanceof String[]) { newValue = getConvertUtils().convert(((String[]) value)[0], type); } else { newValue = convert(value, type); } } // Invoke the setter method try { getPropertyUtils().setProperty(target, name, newValue); } catch (NoSuchMethodException e) { throw new InvocationTargetException(e, "Cannot set " + propName); } }
From source file:org.eclipse.january.dataset.DTypeUtils.java
public static byte[] toByteArray(final Object b, final int itemSize) { byte[] result = null; if (b instanceof Number) { result = new byte[itemSize]; final byte val = ((Number) b).byteValue(); for (int i = 0; i < itemSize; i++) { result[i] = val; }//from w ww . j av a 2 s .c o m } else if (b instanceof byte[]) { result = (byte[]) b; if (result.length < itemSize) { result = new byte[itemSize]; int ilen = result.length; for (int i = 0; i < ilen; i++) { result[i] = ((byte[]) b)[i]; } } } else if (b instanceof List<?>) { result = new byte[itemSize]; List<?> jl = (List<?>) b; int ilen = jl.size(); if (ilen > 0 && !(jl.get(0) instanceof Number)) { logger.error("Given array was not of a numerical primitive type"); throw new IllegalArgumentException("Given array was not of a numerical primitive type"); } ilen = Math.min(itemSize, ilen); for (int i = 0; i < ilen; i++) { result[i] = (byte) toLong(jl.get(i)); } } else if (b.getClass().isArray()) { result = new byte[itemSize]; int ilen = Array.getLength(b); if (ilen > 0 && !(Array.get(b, 0) instanceof Number)) { logger.error("Given array was not of a numerical primitive type"); throw new IllegalArgumentException("Given array was not of a numerical primitive type"); } ilen = Math.min(itemSize, ilen); for (int i = 0; i < ilen; i++) { result[i] = (byte) ((Number) Array.get(b, i)).longValue(); } } else if (b instanceof Complex) { if (itemSize > 2) { logger.error("Complex number will not fit in compound dataset"); throw new IllegalArgumentException("Complex number will not fit in compound dataset"); } Complex cb = (Complex) b; switch (itemSize) { default: case 0: break; case 1: result = new byte[] { (byte) cb.getReal() }; break; case 2: result = new byte[] { (byte) cb.getReal(), (byte) cb.getImaginary() }; break; } } else if (b instanceof Dataset) { Dataset db = (Dataset) b; if (db.getSize() != 1) { logger.error("Given dataset must have only one item"); throw new IllegalArgumentException("Given dataset must have only one item"); } return toByteArray(db.getObjectAbs(0), itemSize); } else if (b instanceof IDataset) { IDataset db = (Dataset) b; if (db.getSize() != 1) { logger.error("Given dataset must have only one item"); throw new IllegalArgumentException("Given dataset must have only one item"); } return toByteArray(db.getObject(new int[db.getRank()]), itemSize); } return result; }
From source file:ArrayUtils.java
/** * Gets the elements that the two arrays have in common. Elements are * retrieved from the first array./* www. j a v a2s . co m*/ * * @param array1 * The first array * @param array2 * The second array * @return The elements in <code>array1</code> that occur at least once in * <code>array2</code> */ public static Object[] commonElementsP(Object array1, Object array2) { int count = 0; if (array1 == null || array2 == null) return new Object[0]; if (!array1.getClass().isArray() || array2.getClass().isArray()) return new Object[0]; int len1 = Array.getLength(array1); int len2 = Array.getLength(array2); int i, j; for (i = 0; i < len1; i++) for (j = 0; j < len2; j++) if (equals(Array.get(array1, i), Array.get(array2, j))) { count++; break; } Object[] ret = new Object[count]; count = 0; for (i = 0; i < len1; i++) for (j = 0; j < len2; j++) if (equals(Array.get(array1, i), Array.get(array2, j))) { ret[count] = Array.get(array1, i); count++; break; } return ret; }
From source file:com.github.dozermapper.core.MappingProcessor.java
private Object addToPrimitiveArray(Object srcObj, FieldMap fieldMap, int size, Object srcCollectionValue, Object destObj, Class<?> destEntryType) { Object result;//from w ww. j a va 2 s . co m Object field = fieldMap.getDestValue(destObj); int arraySize = 0; if (field == null) { result = Array.newInstance(destEntryType, size); } else { result = Array.newInstance(destEntryType, size + Array.getLength(field)); arraySize = Array.getLength(field); System.arraycopy(field, 0, result, 0, arraySize); } // primitive arrays are ALWAYS cumulative for (int i = 0; i < size; i++) { CopyByReferenceContainer copyByReferences = globalConfiguration.getCopyByReferences(); Object toValue; if (srcCollectionValue != null && copyByReferences.contains(srcCollectionValue.getClass())) { toValue = srcCollectionValue; } else { toValue = mapOrRecurseObject(srcObj, Array.get(srcCollectionValue, i), destEntryType, fieldMap, destObj); } Array.set(result, arraySize, toValue); arraySize++; } return result; }
From source file:br.msf.commons.text.EnhancedStringBuilder.java
protected static void format(final Object object, final StringBuilder builder) { if (object == null) { return;// www . j ava 2s . c o m } if (ObjectUtils.isCharSequence(object)) { builder.append((CharSequence) object); } else if (ObjectUtils.isCharacter(object)) { builder.append((Character) object); } else if (ObjectUtils.isNumber(object)) { builder.append(NumberUtils.format((Number) object)); } else if (ObjectUtils.isDate(object) || ObjectUtils.isCalendar(object)) { builder.append(DateUtils.formatDateTime(object)); } else if (ObjectUtils.isArray(object)) { int size = Array.getLength(object); builder.ensureCapacity(builder.length() + (size)); for (int i = 0; i < size; i++) { format(Array.get(object, i), builder); } } else if (ObjectUtils.isCollection(object)) { Collection<?> collection = (Collection) object; for (Object item : collection) { format(item, builder); } } else { builder.append(object); } }
From source file:com.betfair.cougar.netutil.nio.marshalling.SocketRMIMarshallerTest.java
/** * Equals methods in generated idd classes don't handle delegates * @param result/*from w w w .j a v a2 s .c o m*/ * @return * @throws Exception */ private Object removeDelegates(Object result) throws Exception { if (!(result instanceof Transcribable)) { return result; } Transcribable transcribable = (Transcribable) result; final Object[] objects = new Object[transcribable.getParameters().length]; final int[] index = new int[1]; transcribable.transcribe(new TranscriptionOutput() { @Override public void writeObject(Object obj, Parameter param, boolean client) throws Exception { if (obj == null) { objects[index[0]++] = null; } else if (param.getParameterType().getType() == Type.OBJECT) { objects[index[0]++] = removeDelegates(obj); } else if (param.getParameterType().getType() == Type.LIST) { if (obj.getClass().isArray()) { objects[index[0]] = Array.newInstance( param.getParameterType().getComponentTypes()[0].getImplementationClass(), Array.getLength(obj)); for (int i = 0, limit = Array.getLength(obj); i < limit; i++) { Array.set(objects[index[0]], i, removeDelegates(Array.get(obj, i))); } index[0]++; } else { List list = (List) obj; objects[index[0]] = new ArrayList(); for (Object o : list) { ((List) objects[index[0]]).add(removeDelegates(o)); } index[0]++; } } else if (param.getParameterType().getType() == Type.SET) { Set set = (Set) obj; objects[index[0]] = new HashSet(); for (Object o : set) { ((Set) objects[index[0]]).add(removeDelegates(o)); } index[0]++; } else if (param.getParameterType().getType() == Type.MAP) { Map<Object, Object> map = (Map) obj; objects[index[0]] = new HashMap(); for (Entry entry : map.entrySet()) { ((Map) objects[index[0]]).put(removeDelegates(entry.getKey()), removeDelegates(entry.getValue())); } index[0]++; } else { objects[index[0]++] = obj; } } }, TranscribableParams.getAll(), false); Transcribable newObject = (Transcribable) result.getClass().newInstance(); index[0] = 0; newObject.transcribe(new TranscriptionInput() { @Override public <T> T readObject(Parameter param, boolean client) throws Exception { return (T) objects[index[0]++]; } }, TranscribableParams.getAll(), false); return newObject; }
From source file:ArrayUtils.java
/** * Gets the elements that are in array1, but not array 2. * // ww w . j a va 2 s . co m * @param array1 * The first array * @param array2 * The second array * @return The elements in <code>array1</code> that do not occur in * <code>array2</code> */ public static Object[] removedElementsP(Object array1, Object array2) { int count = 0; if (array1 == null || array2 == null) return new Object[0]; if (!array1.getClass().isArray() || array2.getClass().isArray()) return new Object[0]; int len1 = Array.getLength(array1); int len2 = Array.getLength(array2); int i, j; for (i = 0; i < len1; i++) { count++; for (j = 0; j < len2; j++) { if (equals(Array.get(array1, i), Array.get(array2, j))) { count--; break; } } } Object[] ret = new Object[count]; count = 0; for (i = 0; i < len1; i++) { count++; for (j = 0; j < len2; j++) { if (equals(Array.get(array1, i), Array.get(array2, j))) { count--; break; } ret[count] = Array.get(array1, i); } } return ret; }