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:com.microsoft.tfs.core.internal.db.DBStatement.java
/** * Convenience query that returns an array of a primitive component type. *///from w w w.j a v a2 s .c om public Object executeQueryForPrimitiveArray(final Object params, final Class primitiveType) { if (primitiveType == null || !primitiveType.isPrimitive()) { throw new IllegalArgumentException("primitiveType must be a non-null primitive type"); //$NON-NLS-1$ } final List results = new ArrayList(); executeQuery(params, new ResultHandler() { @Override public void handleRow(final ResultSet rset) throws SQLException { results.add(rset.getObject(1)); } }); final int len = results.size(); final Object returnArray = Array.newInstance(primitiveType, len); for (int i = 0; i < len; i++) { Array.set(returnArray, i, results.get(i)); } return returnArray; }
From source file:org.istsms.util.Javabean2JSON.java
public static Object fromJSONArray(JSONArray jArr, Class arrayType) { if (jArr != null && arrayType != null) { Class baseType = arrayType.getComponentType(); if (baseType == null) return null; //it was not an array! String baseTypeName = baseType.getCanonicalName(); int length = jArr.length(); Object argArray = Array.newInstance(baseType, length); try {// w ww .j a v a 2s. co m Vector v = new Vector(); for (int j = 0; j < jArr.length(); j++) { //four cases: the json Array element may be: //a. a JSON Array (in case of array of arrays) //b. a calendar //c. a JSON Object //d. a primitive value (serialized as a String) Object jElement = jArr.get(j); if (jElement.equals(null)) continue; if (jElement instanceof JSONArray) { Object element = fromJSONArray((JSONArray) jElement, baseType); if (element != null) Array.set(argArray, j, element); } else if (isCalendar(baseTypeName)) { Object element = toJavaCalendar((JSONObject) jElement); if (element != null) Array.set(argArray, j, element); } else if (jElement instanceof JSONObject) { Object element = fromJSONObject((JSONObject) jElement, baseType); if (element != null) Array.set(argArray, j, element); } else { Object primitive = getPrimitive(jArr.getString(j), baseTypeName); if (primitive != null) Array.set(argArray, j, primitive); } } return argArray; } catch (NegativeArraySizeException e) { } catch (JSONException e) { } } return null; }
From source file:org.apache.geode.management.internal.cli.util.JsonUtil.java
private static Object toArray(Object value, Class<?> parameterType) throws GfJsonException { Class arrayComponentType = parameterType.getComponentType(); if (isPrimitiveOrWrapper(arrayComponentType)) { if (value instanceof JSONArray) { try { JSONArray jsonArray = (JSONArray) value; Object jArray = Array.newInstance(arrayComponentType, jsonArray.length()); for (int i = 0; i < jsonArray.length(); i++) { Array.set(jArray, i, jsonArray.get(i)); }// w ww. j a v a2 s . c o m return jArray; } catch (ArrayIndexOutOfBoundsException e) { throw new GfJsonException(e); } catch (IllegalArgumentException e) { throw new GfJsonException(e); } catch (JSONException e) { throw new GfJsonException(e); } } else { throw new GfJsonException("Expected JSONArray for array type"); } } else throw new GfJsonException( "Array contains non-primitive element. Non-primitive elements are not supported in json array"); }
From source file:org.unitils.mock.core.proxy.CloneUtil.java
/** * Clones the given array and all it's elements. * * @param arrayToClone The array, not null * @param cloneCache The cached clones, not null * @return The cloned array, not null//www . j av a 2 s . c om */ protected static Object cloneArray(Object arrayToClone, Map<Object, Object> cloneCache) throws Throwable { int lenght = Array.getLength(arrayToClone); Object clonedArray = Array.newInstance(arrayToClone.getClass().getComponentType(), lenght); // Make sure we put the array in the cache before we start cloning the elements, since the array itself may also // be one of the elements, and in this case we want to reuse the same element, to avoid infinite recursion. cloneCache.put(arrayToClone, clonedArray); for (int i = 0; i < lenght; i++) { Object elementValue = Array.get(arrayToClone, i); Object clonedElementValue = cloneObject(elementValue, cloneCache); Array.set(clonedArray, i, clonedElementValue); } return clonedArray; }
From source file:com.medallia.spider.api.DynamicInputImpl.java
private static Object parseSingleValue(Class<?> rt, String v, AnnotatedElement anno, Map<Class<?>, InputArgParser<?>> inputArgParsers) { if (rt.isEnum()) { String vlow = v.toLowerCase(); for (Enum e : rt.asSubclass(Enum.class).getEnumConstants()) { if (e.name().toLowerCase().equals(vlow)) return e; }//from w w w. jav a 2 s. c o m throw new AssertionError("Enum constant not found: " + v); } else if (rt == Integer.class) { // map blank strings to null return Strings.hasContent(v) ? Integer.valueOf(v) : null; } else if (rt == Integer.TYPE) { // primitive int must have a value return Integer.valueOf(v); } else if (rt == Long.class) { // map blank strings to null return Strings.hasContent(v) ? Long.valueOf(v) : null; } else if (rt == Long.TYPE) { // primitive long must have a value return Long.valueOf(v); } else if (rt == Double.class) { // map blank strings to null return Strings.hasContent(v) ? Double.valueOf(v) : null; } else if (rt == Double.TYPE) { // primitive double must have a value return Double.valueOf(v); } else if (rt == String.class) { return v; } else if (rt.isArray()) { Input.List ann = anno.getAnnotation(Input.List.class); if (ann == null) throw new AssertionError("Array type but no annotation (see " + Input.class + "): " + anno); String separator = ann.separator(); String[] strVals = v.split(separator, -1); Class<?> arrayType = rt.getComponentType(); Object a = Array.newInstance(arrayType, strVals.length); for (int i = 0; i < strVals.length; i++) { Array.set(a, i, parseSingleValue(arrayType, strVals[i], anno, inputArgParsers)); } return a; } else if (inputArgParsers != null) { InputArgParser<?> argParser = inputArgParsers.get(rt); if (argParser != null) { return argParser.parse(v); } } throw new AssertionError("Unknown return type " + rt + " (val: " + v + ")"); }
From source file:org.sjmvc.binding.AbstractBinder.java
/** * Set the values in an array property.//from w w w .j a v a2 s . c o m * * @param field The field to set. * @param currentObject The object being processed. * @param name The name of the array property. * @param values The values to set. * @throws Exception If the values cannot be set in the array property. */ protected void setArrayValues(Field field, Object currentObject, String name, String values[]) throws Exception { LOGGER.trace("Setting [{}] to {} array", StringUtils.join(values, ", "), name); Class<?> elementsType = field.getType().getComponentType(); Object array = Array.newInstance(elementsType, values.length); for (int i = 0; i < values.length; i++) { Array.set(array, i, ReflectionUtils.fromString(elementsType, values[i])); } // Save the array in the object ReflectionUtils.setValue(currentObject, name, array); }
From source file:org.primeframework.mvc.parameter.convert.AbstractGlobalConverter.java
/** * This performs the conversion from an array of String values to an array of the given type. * * @param values The values to convert to an array. * @param convertTo The array type to convert to. * @param dynamicAttributes The dynamic attributes to assist in the conversion. * @param expression The full path to the expression that is causing the conversion. * @return The converted value.//from w w w . j a v a 2 s . c o m * @throws ConversionException If the conversion failed. * @throws ConverterStateException if the converter didn't have all of the information it needed to perform the * conversion. */ protected Object stringsToArray(String[] values, Type convertTo, Map<String, String> dynamicAttributes, String expression) throws ConversionException { if (values == null) { return null; } Object finalArray; Class<?> rawType = TypeTools.rawType(convertTo); if (values.length == 0) { finalArray = Array.newInstance(rawType.getComponentType(), 0); } else { finalArray = Array.newInstance(rawType.getComponentType(), values.length); for (int i = 0; i < values.length; i++) { Object singleValue = stringToObject(values[i], rawType.getComponentType(), dynamicAttributes, expression); Array.set(finalArray, i, singleValue); } } return finalArray; }
From source file:org.apache.openjpa.kernel.ResultPacker.java
/** * Pack the given array into an instance of the query's result class. */// w w w . j a v a2 s .c o m public Object pack(Object[] result) { if (result == null || result.length == 0) return null; // special cases for object arrays and maps if (_resultClass == Object[].class) { // the result might contain extra data at the end if (result.length > _aliases.length) { Object[] trim = new Object[_aliases.length]; System.arraycopy(result, 0, trim, 0, trim.length); return trim; } return result; } if (_resultClass.isArray()) { Class<?> elementType = _resultClass.getComponentType(); Object castResult = Array.newInstance(elementType, result.length); for (int i = 0; i < result.length; i++) Array.set(castResult, i, elementType.cast(result[i])); return castResult; } if (_resultClass == Object.class) return result[0]; if (_resultClass == HashMap.class || _resultClass == Map.class) { Map<String, Object> map = new HashMap<String, Object>(result.length); for (int i = 0; i < _aliases.length; i++) map.put(_aliases[i], result[i]); return map; } // primitive or simple type? if (_sets == null && _constructor == null) return Filters.convert(result[0], _resultClass); // must be a user-defined type return packUserType(result); }
From source file:org.drools.core.xml.jaxb.util.JaxbUnknownAdapter.java
public Object recursiveUnmarhsal(Object o) throws Exception { if (o instanceof JaxbListWrapper) { JaxbListWrapper wrapper = (JaxbListWrapper) o; Object[] elements = wrapper.getElements(); int size = 0; if (elements != null) { size = elements.length;/*from w w w .j a va2 s. c om*/ } if (wrapper.getType() == null) { List<Object> list = new ArrayList<Object>(size); return convertSerializedElementsToCollection(elements, list); } else { switch (wrapper.getType()) { case LIST: List<Object> list = new ArrayList<Object>(size); return convertSerializedElementsToCollection(elements, list); case SET: Set<Object> set = new HashSet<Object>(size); return convertSerializedElementsToCollection(elements, set); case MAP: Map<String, Object> map = new HashMap<String, Object>(size); if (size > 0) { for (Object keyValueObj : elements) { JaxbStringObjectPair keyValue = (JaxbStringObjectPair) keyValueObj; Object key = keyValue.getKey(); Object value = convertSerializedObjectToObject(keyValue.getValue()); map.put(key.toString(), value); } } return map; case ARRAY: Object[] objArr = wrapper.getElements(); int length = objArr.length; String componentTypeName = wrapper.getComponentType(); Class realArrComponentType = null; realArrComponentType = getClass(componentTypeName); // create and fill array Object realArr = Array.newInstance(realArrComponentType, objArr.length); for (int i = 0; i < length; ++i) { Array.set(realArr, i, convertSerializedObjectToObject(objArr[i])); } return realArr; default: throw new IllegalArgumentException( "Unknown JAXB collection wrapper type: " + wrapper.getType().toString()); } } } else if (o instanceof JaxbStringObjectPair[]) { // backwards compatibile: remove in 7.0.x JaxbStringObjectPair[] value = (JaxbStringObjectPair[]) o; Map<Object, Object> r = new HashMap<Object, Object>(); for (JaxbStringObjectPair p : value) { if (p.getValue() instanceof JaxbListWrapper) { r.put(p.getKey(), new ArrayList(Arrays.asList(((JaxbListWrapper) p.getValue()).getElements()))); } else { r.put(p.getKey(), p.getValue()); } } return r; } else { return o; } }
From source file:org.jdto.impl.CoreBeanModifier.java
private Object copyToProperArray(Class expectedType, Object finalValue) { Object ret = Array.newInstance(expectedType.getComponentType(), Array.getLength(finalValue)); for (int i = 0; i < Array.getLength(finalValue); i++) { Array.set(ret, i, Array.get(finalValue, i)); }//from w w w.j av a 2 s . co m return ret; }