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.springframework.beans.TypeConverterDelegate.java
private Object convertToTypedArray(Object input, @Nullable String propertyName, Class<?> componentType) { if (input instanceof Collection) { // Convert Collection elements to array elements. Collection<?> coll = (Collection<?>) input; Object result = Array.newInstance(componentType, coll.size()); int i = 0; for (Iterator<?> it = coll.iterator(); it.hasNext(); i++) { Object value = convertIfNecessary(buildIndexedPropertyName(propertyName, i), null, it.next(), componentType);//from w w w . j a v a 2 s. c om Array.set(result, i, value); } return result; } else if (input.getClass().isArray()) { // Convert array elements, if necessary. if (componentType.equals(input.getClass().getComponentType()) && !this.propertyEditorRegistry.hasCustomEditorForElement(componentType, propertyName)) { return input; } int arrayLength = Array.getLength(input); Object result = Array.newInstance(componentType, arrayLength); for (int i = 0; i < arrayLength; i++) { Object value = convertIfNecessary(buildIndexedPropertyName(propertyName, i), null, Array.get(input, 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 = convertIfNecessary(buildIndexedPropertyName(propertyName, 0), null, input, componentType); Array.set(result, 0, value); return result; } }
From source file:javadz.beanutils.LazyDynaBean.java
/** * Grow the size of an indexed property//ww w . ja v a 2 s .co m * @param name The name of the property * @param indexedProperty The current property value * @param index The indexed value to grow the property to (i.e. one less than * the required size) * @return The new property value (grown to the appropriate size) */ protected Object growIndexedProperty(String name, Object indexedProperty, int index) { // Grow a List to the appropriate size if (indexedProperty instanceof List) { List list = (List) indexedProperty; while (index >= list.size()) { Class contentType = getDynaClass().getDynaProperty(name).getContentType(); Object value = null; if (contentType != null) { value = createProperty(name + "[" + list.size() + "]", contentType); } list.add(value); } } // Grow an Array to the appropriate size if ((indexedProperty.getClass().isArray())) { int length = Array.getLength(indexedProperty); if (index >= length) { Class componentType = indexedProperty.getClass().getComponentType(); Object newArray = Array.newInstance(componentType, (index + 1)); System.arraycopy(indexedProperty, 0, newArray, 0, length); indexedProperty = newArray; set(name, indexedProperty); int newLength = Array.getLength(indexedProperty); for (int i = length; i < newLength; i++) { Array.set(indexedProperty, i, createProperty(name + "[" + i + "]", componentType)); } } } return indexedProperty; }
From source file:com.android.camera2.its.ItsSerializer.java
@SuppressWarnings("unchecked") public static CaptureRequest.Builder deserialize(CaptureRequest.Builder mdDefault, JSONObject jsonReq) throws ItsException { try {//w ww . j a v a2s . c om Logt.i(TAG, "Parsing JSON capture request ..."); // Iterate over the CaptureRequest reflected fields. CaptureRequest.Builder md = mdDefault; Field[] allFields = CaptureRequest.class.getDeclaredFields(); for (Field field : allFields) { if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers()) && field.getType() == CaptureRequest.Key.class && field.getGenericType() instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) field.getGenericType(); Type[] argTypes = paramType.getActualTypeArguments(); if (argTypes.length > 0) { CaptureRequest.Key key = (CaptureRequest.Key) field.get(md); String keyName = key.getName(); Type keyType = argTypes[0]; // For each reflected CaptureRequest entry, look inside the JSON object // to see if it is being set. If it is found, remove the key from the // JSON object. After this process, there should be no keys left in the // JSON (otherwise an invalid key was specified). if (jsonReq.has(keyName) && !jsonReq.isNull(keyName)) { if (keyType instanceof GenericArrayType) { Type elmtType = ((GenericArrayType) keyType).getGenericComponentType(); JSONArray ja = jsonReq.getJSONArray(keyName); Object val[] = new Object[ja.length()]; for (int i = 0; i < ja.length(); i++) { if (elmtType == int.class) { Array.set(val, i, ja.getInt(i)); } else if (elmtType == byte.class) { Array.set(val, i, (byte) ja.getInt(i)); } else if (elmtType == float.class) { Array.set(val, i, (float) ja.getDouble(i)); } else if (elmtType == long.class) { Array.set(val, i, ja.getLong(i)); } else if (elmtType == double.class) { Array.set(val, i, ja.getDouble(i)); } else if (elmtType == boolean.class) { Array.set(val, i, ja.getBoolean(i)); } else if (elmtType == String.class) { Array.set(val, i, ja.getString(i)); } else if (elmtType == Size.class) { JSONObject obj = ja.getJSONObject(i); Array.set(val, i, new Size(obj.getInt("width"), obj.getInt("height"))); } else if (elmtType == Rect.class) { JSONObject obj = ja.getJSONObject(i); Array.set(val, i, new Rect(obj.getInt("left"), obj.getInt("top"), obj.getInt("bottom"), obj.getInt("right"))); } else if (elmtType == Rational.class) { JSONObject obj = ja.getJSONObject(i); Array.set(val, i, new Rational(obj.getInt("numerator"), obj.getInt("denominator"))); } else if (elmtType == RggbChannelVector.class) { JSONArray arr = ja.getJSONArray(i); Array.set(val, i, new RggbChannelVector((float) arr.getDouble(0), (float) arr.getDouble(1), (float) arr.getDouble(2), (float) arr.getDouble(3))); } else if (elmtType == ColorSpaceTransform.class) { JSONArray arr = ja.getJSONArray(i); Rational xform[] = new Rational[9]; for (int j = 0; j < 9; j++) { xform[j] = new Rational(arr.getJSONObject(j).getInt("numerator"), arr.getJSONObject(j).getInt("denominator")); } Array.set(val, i, new ColorSpaceTransform(xform)); } else if (elmtType == MeteringRectangle.class) { JSONObject obj = ja.getJSONObject(i); Array.set(val, i, new MeteringRectangle(obj.getInt("x"), obj.getInt("y"), obj.getInt("width"), obj.getInt("height"), obj.getInt("weight"))); } else { throw new ItsException("Failed to parse key from JSON: " + keyName); } } if (val != null) { Logt.i(TAG, "Set: " + keyName + " -> " + Arrays.toString(val)); md.set(key, val); jsonReq.remove(keyName); } } else { Object val = null; if (keyType == Integer.class) { val = jsonReq.getInt(keyName); } else if (keyType == Byte.class) { val = (byte) jsonReq.getInt(keyName); } else if (keyType == Double.class) { val = jsonReq.getDouble(keyName); } else if (keyType == Long.class) { val = jsonReq.getLong(keyName); } else if (keyType == Float.class) { val = (float) jsonReq.getDouble(keyName); } else if (keyType == Boolean.class) { val = jsonReq.getBoolean(keyName); } else if (keyType == String.class) { val = jsonReq.getString(keyName); } else if (keyType == Size.class) { JSONObject obj = jsonReq.getJSONObject(keyName); val = new Size(obj.getInt("width"), obj.getInt("height")); } else if (keyType == Rect.class) { JSONObject obj = jsonReq.getJSONObject(keyName); val = new Rect(obj.getInt("left"), obj.getInt("top"), obj.getInt("right"), obj.getInt("bottom")); } else if (keyType == Rational.class) { JSONObject obj = jsonReq.getJSONObject(keyName); val = new Rational(obj.getInt("numerator"), obj.getInt("denominator")); } else if (keyType == RggbChannelVector.class) { JSONObject obj = jsonReq.optJSONObject(keyName); JSONArray arr = jsonReq.optJSONArray(keyName); if (arr != null) { val = new RggbChannelVector((float) arr.getDouble(0), (float) arr.getDouble(1), (float) arr.getDouble(2), (float) arr.getDouble(3)); } else if (obj != null) { val = new RggbChannelVector((float) obj.getDouble("red"), (float) obj.getDouble("greenEven"), (float) obj.getDouble("greenOdd"), (float) obj.getDouble("blue")); } else { throw new ItsException("Invalid RggbChannelVector object"); } } else if (keyType == ColorSpaceTransform.class) { JSONArray arr = jsonReq.getJSONArray(keyName); Rational a[] = new Rational[9]; for (int i = 0; i < 9; i++) { a[i] = new Rational(arr.getJSONObject(i).getInt("numerator"), arr.getJSONObject(i).getInt("denominator")); } val = new ColorSpaceTransform(a); } else if (keyType instanceof ParameterizedType && ((ParameterizedType) keyType).getRawType() == Range.class && ((ParameterizedType) keyType).getActualTypeArguments().length == 1 && ((ParameterizedType) keyType) .getActualTypeArguments()[0] == Integer.class) { JSONArray arr = jsonReq.getJSONArray(keyName); val = new Range<Integer>(arr.getInt(0), arr.getInt(1)); } else { throw new ItsException( "Failed to parse key from JSON: " + keyName + ", " + keyType); } if (val != null) { Logt.i(TAG, "Set: " + keyName + " -> " + val); md.set(key, val); jsonReq.remove(keyName); } } } } } } // Ensure that there were no invalid keys in the JSON request object. if (jsonReq.length() != 0) { throw new ItsException("Invalid JSON key(s): " + jsonReq.toString()); } Logt.i(TAG, "Parsing JSON capture request completed"); return md; } catch (java.lang.IllegalAccessException e) { throw new ItsException("Access error: ", e); } catch (org.json.JSONException e) { throw new ItsException("JSON error: ", e); } }
From source file:org.opensha.commons.util.DataUtils.java
/** * Creates a new array from the values in a source array at the specified * indices. Returned array is of same type as source. * /*from w w w. j ava2 s .c om*/ * @param array array source * @param indices index values of items to select * @return a new array of values at indices in source * @throws NullPointerException if {@code array} or * {@code indices} are {@code null} * @throws IllegalArgumentException if data object is not an array or if * data array is empty * @throws IndexOutOfBoundsException if any indices are out of range */ public static Object arraySelect(Object array, int[] indices) { checkNotNull(array, "Supplied data array is null"); checkNotNull(indices, "Supplied index array is null"); checkArgument(array.getClass().isArray(), "Data object supplied is not an array"); int arraySize = Array.getLength(array); checkArgument(arraySize != 0, "Supplied data array is empty"); // validate indices for (int i = 0; i < indices.length; i++) { checkPositionIndex(indices[i], arraySize, "Supplied index"); } Class<? extends Object> srcClass = array.getClass().getComponentType(); Object out = Array.newInstance(srcClass, indices.length); for (int i = 0; i < indices.length; i++) { Array.set(out, i, Array.get(array, indices[i])); } return out; }
From source file:org.apache.hadoop.hbase.security.access.HbaseObjectWritableFor96Migration.java
/** * Read a {@link Writable}, {@link String}, primitive type, or an array of * the preceding.// ww w . j a va 2 s .c o m * @param in * @param objectWritable * @param conf * @return the object * @throws IOException */ @SuppressWarnings("unchecked") static Object readObject(DataInput in, HbaseObjectWritableFor96Migration objectWritable, Configuration conf) throws IOException { Class<?> declaredClass = CODE_TO_CLASS.get(WritableUtils.readVInt(in)); Object instance; if (declaredClass.isPrimitive()) { // primitive types if (declaredClass == Boolean.TYPE) { // boolean instance = Boolean.valueOf(in.readBoolean()); } else if (declaredClass == Character.TYPE) { // char instance = Character.valueOf(in.readChar()); } else if (declaredClass == Byte.TYPE) { // byte instance = Byte.valueOf(in.readByte()); } else if (declaredClass == Short.TYPE) { // short instance = Short.valueOf(in.readShort()); } else if (declaredClass == Integer.TYPE) { // int instance = Integer.valueOf(in.readInt()); } else if (declaredClass == Long.TYPE) { // long instance = Long.valueOf(in.readLong()); } else if (declaredClass == Float.TYPE) { // float instance = Float.valueOf(in.readFloat()); } else if (declaredClass == Double.TYPE) { // double instance = Double.valueOf(in.readDouble()); } else if (declaredClass == Void.TYPE) { // void instance = null; } else { throw new IllegalArgumentException("Not a primitive: " + declaredClass); } } else if (declaredClass.isArray()) { // array if (declaredClass.equals(byte[].class)) { instance = Bytes.readByteArray(in); } else { int length = in.readInt(); instance = Array.newInstance(declaredClass.getComponentType(), length); for (int i = 0; i < length; i++) { Array.set(instance, i, readObject(in, conf)); } } } else if (declaredClass.equals(Array.class)) { //an array not declared in CLASS_TO_CODE Class<?> componentType = readClass(conf, in); int length = in.readInt(); instance = Array.newInstance(componentType, length); for (int i = 0; i < length; i++) { Array.set(instance, i, readObject(in, conf)); } } else if (List.class.isAssignableFrom(declaredClass)) { // List int length = in.readInt(); instance = new ArrayList(length); for (int i = 0; i < length; i++) { ((ArrayList) instance).add(readObject(in, conf)); } } else if (declaredClass == String.class) { // String instance = Text.readString(in); } else if (declaredClass.isEnum()) { // enum instance = Enum.valueOf((Class<? extends Enum>) declaredClass, Text.readString(in)); } else if (declaredClass == Message.class) { String className = Text.readString(in); try { declaredClass = getClassByName(conf, className); instance = tryInstantiateProtobuf(declaredClass, in); } catch (ClassNotFoundException e) { LOG.error("Can't find class " + className, e); throw new IOException("Can't find class " + className, e); } } else if (Scan.class.isAssignableFrom(declaredClass)) { int length = in.readInt(); byte[] scanBytes = new byte[length]; in.readFully(scanBytes); ClientProtos.Scan.Builder scanProto = ClientProtos.Scan.newBuilder(); instance = ProtobufUtil.toScan(scanProto.mergeFrom(scanBytes).build()); } else { // Writable or Serializable Class instanceClass = null; int b = (byte) WritableUtils.readVInt(in); if (b == NOT_ENCODED) { String className = Text.readString(in); try { instanceClass = getClassByName(conf, className); } catch (ClassNotFoundException e) { LOG.error("Can't find class " + className, e); throw new IOException("Can't find class " + className, e); } } else { instanceClass = CODE_TO_CLASS.get(b); } if (Writable.class.isAssignableFrom(instanceClass)) { Writable writable = WritableFactories.newInstance(instanceClass, conf); try { writable.readFields(in); } catch (Exception e) { LOG.error("Error in readFields", e); throw new IOException("Error in readFields", e); } instance = writable; if (instanceClass == NullInstance.class) { // null declaredClass = ((NullInstance) instance).declaredClass; instance = null; } } else { int length = in.readInt(); byte[] objectBytes = new byte[length]; in.readFully(objectBytes); ByteArrayInputStream bis = null; ObjectInputStream ois = null; try { bis = new ByteArrayInputStream(objectBytes); ois = new ObjectInputStream(bis); instance = ois.readObject(); } catch (ClassNotFoundException e) { LOG.error("Class not found when attempting to deserialize object", e); throw new IOException("Class not found when attempting to " + "deserialize object", e); } finally { if (bis != null) bis.close(); if (ois != null) ois.close(); } } } if (objectWritable != null) { // store values objectWritable.declaredClass = declaredClass; objectWritable.instance = instance; } return instance; }
From source file:org.apache.hadoop.hbase.io.HbaseObjectWritable.java
/** * Read a {@link Writable}, {@link String}, primitive type, or an array of * the preceding./* w ww . ja va2 s . c o m*/ * @param in * @param objectWritable * @param conf * @return the object * @throws IOException */ @SuppressWarnings("unchecked") public static Object readObject(DataInput in, HbaseObjectWritable objectWritable, Configuration conf) throws IOException { Class<?> declaredClass = CODE_TO_CLASS.get(WritableUtils.readVInt(in)); Object instance; if (declaredClass.isPrimitive()) { // primitive types if (declaredClass == Boolean.TYPE) { // boolean instance = Boolean.valueOf(in.readBoolean()); } else if (declaredClass == Character.TYPE) { // char instance = Character.valueOf(in.readChar()); } else if (declaredClass == Byte.TYPE) { // byte instance = Byte.valueOf(in.readByte()); } else if (declaredClass == Short.TYPE) { // short instance = Short.valueOf(in.readShort()); } else if (declaredClass == Integer.TYPE) { // int instance = Integer.valueOf(in.readInt()); } else if (declaredClass == Long.TYPE) { // long instance = Long.valueOf(in.readLong()); } else if (declaredClass == Float.TYPE) { // float instance = Float.valueOf(in.readFloat()); } else if (declaredClass == Double.TYPE) { // double instance = Double.valueOf(in.readDouble()); } else if (declaredClass == Void.TYPE) { // void instance = null; } else { throw new IllegalArgumentException("Not a primitive: " + declaredClass); } } else if (declaredClass.isArray()) { // array if (declaredClass.equals(byte[].class)) { instance = Bytes.readByteArray(in); } else if (declaredClass.equals(Result[].class)) { instance = Result.readArray(in); } else { int length = in.readInt(); instance = Array.newInstance(declaredClass.getComponentType(), length); for (int i = 0; i < length; i++) { Array.set(instance, i, readObject(in, conf)); } } } else if (declaredClass.equals(Array.class)) { //an array not declared in CLASS_TO_CODE Class<?> componentType = readClass(conf, in); int length = in.readInt(); instance = Array.newInstance(componentType, length); for (int i = 0; i < length; i++) { Array.set(instance, i, readObject(in, conf)); } } else if (List.class.isAssignableFrom(declaredClass)) { // List int length = in.readInt(); instance = new ArrayList(length); for (int i = 0; i < length; i++) { ((ArrayList) instance).add(readObject(in, conf)); } } else if (declaredClass == String.class) { // String instance = Text.readString(in); } else if (declaredClass.isEnum()) { // enum instance = Enum.valueOf((Class<? extends Enum>) declaredClass, Text.readString(in)); } else if (declaredClass == Message.class) { String className = Text.readString(in); try { declaredClass = getClassByName(conf, className); instance = tryInstantiateProtobuf(declaredClass, in); } catch (ClassNotFoundException e) { LOG.error("Can't find class " + className, e); throw new IOException("Can't find class " + className, e); } } else { // Writable or Serializable Class instanceClass = null; int b = (byte) WritableUtils.readVInt(in); if (b == NOT_ENCODED) { String className = Text.readString(in); try { instanceClass = getClassByName(conf, className); } catch (ClassNotFoundException e) { LOG.error("Can't find class " + className, e); throw new IOException("Can't find class " + className, e); } } else { instanceClass = CODE_TO_CLASS.get(b); } if (Writable.class.isAssignableFrom(instanceClass)) { Writable writable = WritableFactories.newInstance(instanceClass, conf); try { writable.readFields(in); } catch (Exception e) { LOG.error("Error in readFields", e); throw new IOException("Error in readFields", e); } instance = writable; if (instanceClass == NullInstance.class) { // null declaredClass = ((NullInstance) instance).declaredClass; instance = null; } } else { int length = in.readInt(); byte[] objectBytes = new byte[length]; in.readFully(objectBytes); ByteArrayInputStream bis = null; ObjectInputStream ois = null; try { bis = new ByteArrayInputStream(objectBytes); ois = new ObjectInputStream(bis); instance = ois.readObject(); } catch (ClassNotFoundException e) { LOG.error("Class not found when attempting to deserialize object", e); throw new IOException("Class not found when attempting to " + "deserialize object", e); } finally { if (bis != null) bis.close(); if (ois != null) ois.close(); } } } if (objectWritable != null) { // store values objectWritable.declaredClass = declaredClass; objectWritable.instance = instance; } return instance; }
From source file:org.springframework.jmx.access.MBeanClientInterceptor.java
private Object convertDataArrayToTargetArray(Object[] array, Class<?> targetClass) throws NoSuchMethodException { Class<?> targetType = targetClass.getComponentType(); Method fromMethod = targetType.getMethod("from", array.getClass().getComponentType()); Object resultArray = Array.newInstance(targetType, array.length); for (int i = 0; i < array.length; i++) { Array.set(resultArray, i, ReflectionUtils.invokeMethod(fromMethod, null, array[i])); }/* w ww.ja v a 2 s . c om*/ return resultArray; }
From source file:org.browsermob.proxy.jetty.xml.XmlConfiguration.java
private Object newArray(Object obj, XmlParser.Node node) throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, IllegalAccessException { // Get the type Class aClass = java.lang.Object.class; String type = node.getAttribute("type"); String id = node.getAttribute("id"); if (type != null) { aClass = TypeUtil.fromName(type); if (aClass == null) { if ("String".equals(type)) aClass = java.lang.String.class; else if ("URL".equals(type)) aClass = java.net.URL.class; else if ("InetAddress".equals(type)) aClass = java.net.InetAddress.class; else if ("InetAddrPort".equals(type)) aClass = org.browsermob.proxy.jetty.util.InetAddrPort.class; else//from w w w . j a v a 2 s .c o m aClass = Loader.loadClass(XmlConfiguration.class, type); } } Object array = Array.newInstance(aClass, node.size()); if (id != null) _idMap.put(id, obj); for (int i = 0; i < node.size(); i++) { Object o = node.get(i); if (o instanceof String) continue; XmlParser.Node item = (XmlParser.Node) o; if (!item.getTag().equals("Item")) throw new IllegalStateException("Not an Item"); id = item.getAttribute("id"); Object v = value(obj, item); if (v != null) Array.set(array, i, v); if (id != null) _idMap.put(id, v); } return array; }
From source file:net.lightbody.bmp.proxy.jetty.xml.XmlConfiguration.java
private Object newArray(Object obj, XmlParser.Node node) throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, IllegalAccessException { // Get the type Class aClass = java.lang.Object.class; String type = node.getAttribute("type"); String id = node.getAttribute("id"); if (type != null) { aClass = TypeUtil.fromName(type); if (aClass == null) { if ("String".equals(type)) aClass = java.lang.String.class; else if ("URL".equals(type)) aClass = java.net.URL.class; else if ("InetAddress".equals(type)) aClass = java.net.InetAddress.class; else if ("InetAddrPort".equals(type)) aClass = net.lightbody.bmp.proxy.jetty.util.InetAddrPort.class; else/* w w w . j av a 2 s . c om*/ aClass = Loader.loadClass(XmlConfiguration.class, type); } } Object array = Array.newInstance(aClass, node.size()); if (id != null) _idMap.put(id, obj); for (int i = 0; i < node.size(); i++) { Object o = node.get(i); if (o instanceof String) continue; XmlParser.Node item = (XmlParser.Node) o; if (!item.getTag().equals("Item")) throw new IllegalStateException("Not an Item"); id = item.getAttribute("id"); Object v = value(obj, item); if (v != null) Array.set(array, i, v); if (id != null) _idMap.put(id, v); } return array; }
From source file:Main.java
/** * Underlying implementation of add(array, index, element) methods. * The last parameter is the class, which may not equal element.getClass * for primitives./* w w w. j a va 2 s.c om*/ * * @param array the array to add the element to, may be {@code null} * @param index the position of the new object * @param element the object to add * @param clss the type of the element being added * @return A new array containing the existing elements and the new element */ private static Object add(Object array, int index, Object element, Class<?> clss) { if (array == null) { if (index != 0) { throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0"); } Object joinedArray = Array.newInstance(clss, 1); Array.set(joinedArray, 0, element); return joinedArray; } int length = Array.getLength(array); if (index > length || index < 0) { throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length); } Object result = Array.newInstance(clss, length + 1); System.arraycopy(array, 0, result, 0, index); Array.set(result, index, element); if (index < length) { System.arraycopy(array, index, result, index + 1, length - index); } return result; }