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:org.eclipse.dataset.AbstractCompoundDataset.java
public static long[] toLongArray(final Object b, final int itemSize) { long[] result = null; if (b instanceof Number) { result = new long[itemSize]; long val = ((Number) b).longValue(); for (int i = 0; i < itemSize; i++) result[i] = val; } else if (b instanceof long[]) { result = (long[]) b; if (result.length < itemSize) { result = new long[itemSize]; int ilen = result.length; for (int i = 0; i < ilen; i++) result[i] = ((long[]) b)[i]; }/*from w w w .j a v a 2s. co m*/ } else if (b instanceof List<?>) { result = new long[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] = toLong(jl.get(i)); } } else if (b.getClass().isArray()) { result = new long[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] = ((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 long[] { (long) cb.getReal() }; break; case 2: result = new long[] { (long) cb.getReal(), (long) 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 toLongArray(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 toLongArray(db.getObject(new int[db.getRank()]), itemSize); } return result; }
From source file:org.apache.hadoop.hbase.security.access.HbaseObjectWritableFor96Migration.java
/** * Write a {@link Writable}, {@link String}, primitive type, or an array of * the preceding.//w w w .j a va 2 s. c o m * @param out * @param instance * @param declaredClass * @param conf * @throws IOException */ @SuppressWarnings("unchecked") static void writeObject(DataOutput out, Object instance, Class declaredClass, Configuration conf) throws IOException { Object instanceObj = instance; Class declClass = declaredClass; if (instanceObj == null) { // null instanceObj = new NullInstance(declClass, conf); declClass = Writable.class; } writeClassCode(out, declClass); if (declClass.isArray()) { // array // If bytearray, just dump it out -- avoid the recursion and // byte-at-a-time we were previously doing. if (declClass.equals(byte[].class)) { Bytes.writeByteArray(out, (byte[]) instanceObj); } else { //if it is a Generic array, write the element's type if (getClassCode(declaredClass) == GENERIC_ARRAY_CODE) { Class<?> componentType = declaredClass.getComponentType(); writeClass(out, componentType); } int length = Array.getLength(instanceObj); out.writeInt(length); for (int i = 0; i < length; i++) { Object item = Array.get(instanceObj, i); writeObject(out, item, item.getClass(), conf); } } } else if (List.class.isAssignableFrom(declClass)) { List list = (List) instanceObj; int length = list.size(); out.writeInt(length); for (int i = 0; i < length; i++) { Object elem = list.get(i); writeObject(out, elem, elem == null ? Writable.class : elem.getClass(), conf); } } else if (declClass == String.class) { // String Text.writeString(out, (String) instanceObj); } else if (declClass.isPrimitive()) { // primitive type if (declClass == Boolean.TYPE) { // boolean out.writeBoolean(((Boolean) instanceObj).booleanValue()); } else if (declClass == Character.TYPE) { // char out.writeChar(((Character) instanceObj).charValue()); } else if (declClass == Byte.TYPE) { // byte out.writeByte(((Byte) instanceObj).byteValue()); } else if (declClass == Short.TYPE) { // short out.writeShort(((Short) instanceObj).shortValue()); } else if (declClass == Integer.TYPE) { // int out.writeInt(((Integer) instanceObj).intValue()); } else if (declClass == Long.TYPE) { // long out.writeLong(((Long) instanceObj).longValue()); } else if (declClass == Float.TYPE) { // float out.writeFloat(((Float) instanceObj).floatValue()); } else if (declClass == Double.TYPE) { // double out.writeDouble(((Double) instanceObj).doubleValue()); } else if (declClass == Void.TYPE) { // void } else { throw new IllegalArgumentException("Not a primitive: " + declClass); } } else if (declClass.isEnum()) { // enum Text.writeString(out, ((Enum) instanceObj).name()); } else if (Message.class.isAssignableFrom(declaredClass)) { Text.writeString(out, instanceObj.getClass().getName()); ((Message) instance).writeDelimitedTo(DataOutputOutputStream.constructOutputStream(out)); } else if (Writable.class.isAssignableFrom(declClass)) { // Writable Class<?> c = instanceObj.getClass(); Integer code = CLASS_TO_CODE.get(c); if (code == null) { out.writeByte(NOT_ENCODED); Text.writeString(out, c.getName()); } else { writeClassCode(out, c); } ((Writable) instanceObj).write(out); } else if (Serializable.class.isAssignableFrom(declClass)) { Class<?> c = instanceObj.getClass(); Integer code = CLASS_TO_CODE.get(c); if (code == null) { out.writeByte(NOT_ENCODED); Text.writeString(out, c.getName()); } else { writeClassCode(out, c); } ByteArrayOutputStream bos = null; ObjectOutputStream oos = null; try { bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); oos.writeObject(instanceObj); byte[] value = bos.toByteArray(); out.writeInt(value.length); out.write(value); } finally { if (bos != null) bos.close(); if (oos != null) oos.close(); } } else if (Scan.class.isAssignableFrom(declClass)) { Scan scan = (Scan) instanceObj; byte[] scanBytes = ProtobufUtil.toScan(scan).toByteArray(); out.writeInt(scanBytes.length); out.write(scanBytes); } else { throw new IOException("Can't write: " + instanceObj + " as " + declClass); } }
From source file:org.jfree.chart.demo.SymbolicXYPlotDemo.java
/** * Transform an primitive array to an object array. * /*from w w w.ja va2 s. c o m*/ * @param arr * the array. * @return an array. */ private static Object toArray(final Object arr) { if (arr == null) { return arr; } final Class cls = arr.getClass(); if (!cls.isArray()) { return arr; } Class compType = cls.getComponentType(); int dim = 1; while (!compType.isPrimitive()) { if (!compType.isArray()) { return arr; } else { dim++; compType = compType.getComponentType(); } } final int[] length = new int[dim]; length[0] = Array.getLength(arr); Object[] newarr = null; try { if (compType.equals(Integer.TYPE)) { newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Integer"), length); } else if (compType.equals(Double.TYPE)) { newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Double"), length); } else if (compType.equals(Long.TYPE)) { newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Long"), length); } else if (compType.equals(Float.TYPE)) { newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Float"), length); } else if (compType.equals(Short.TYPE)) { newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Short"), length); } else if (compType.equals(Byte.TYPE)) { newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Byte"), length); } else if (compType.equals(Character.TYPE)) { newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Character"), length); } else if (compType.equals(Boolean.TYPE)) { newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Boolean"), length); } } catch (ClassNotFoundException ex) { System.out.println(ex); } for (int i = 0; i < length[0]; i++) { if (dim != 1) { newarr[i] = toArray(Array.get(arr, i)); } else { newarr[i] = Array.get(arr, i); } } return newarr; }
From source file:org.neo4j.unsafe.impl.batchimport.ParallelBatchImporterTest.java
private void assertPropertyValueEquals(InputEntity input, PropertyContainer entity, String key, Object expected, Object array) {/*from ww w .j av a2 s.com*/ if (expected.getClass().isArray()) { int length = Array.getLength(expected); assertEquals(input + ", " + entity, length, Array.getLength(array)); for (int i = 0; i < length; i++) { assertPropertyValueEquals(input, entity, key, Array.get(expected, i), Array.get(array, i)); } } else { assertEquals(input + ", " + entity + " for key:" + key, expected, array); } }
From source file:org.mqnaas.core.impl.slicing.SliceAdministration.java
/** * Specifies and sets the upper bounds of each dimension of the slice information. It's generic for all number of dimendsions. * // w ww .j a v a 2 s. c o m * @param ubs * Array where the upper bounds will be stored. */ private void initUpperBounds(int[] ubs) { Object it = currentData; for (int i = 0; i < ubs.length; i++) { ubs[i] = Array.getLength(it) - 1; it = Array.get(it, 0); } }
From source file:ArrayUtils.java
/** * @param anArray/*from www . jav a 2 s . c o m*/ * The array to search * @param anElement * The element to search for * @return The first index <code>0<=idx<anArray.length</code> such * that {@link #equals(Object, Object)} returns true for both * <code>anArray[idx]</code> and <code>anElement</code>, or -1 if no * such index exists */ public static int indexOfP(Object anArray, Object anElement) { if (anArray == null) return -1; if (anArray instanceof Object[]) { Object[] array2 = (Object[]) anArray; for (int i = 0; i < array2.length; i++) { if (equals(array2[i], anElement)) return i; } return -1; } else { int i, len; len = Array.getLength(anArray); for (i = 0; i < len; i++) { if (equals(Array.get(anArray, i), anElement)) return i; } return -1; } }
From source file:org.apache.hadoop.hbase.io.HbaseObjectWritable.java
/** * Write a {@link Writable}, {@link String}, primitive type, or an array of * the preceding.// w w w. j a v a 2 s . c om * @param out * @param instance * @param declaredClass * @param conf * @throws IOException */ @SuppressWarnings("unchecked") public static void writeObject(DataOutput out, Object instance, Class declaredClass, Configuration conf) throws IOException { Object instanceObj = instance; Class declClass = declaredClass; if (instanceObj == null) { // null instanceObj = new NullInstance(declClass, conf); declClass = Writable.class; } writeClassCode(out, declClass); if (declClass.isArray()) { // array // If bytearray, just dump it out -- avoid the recursion and // byte-at-a-time we were previously doing. if (declClass.equals(byte[].class)) { Bytes.writeByteArray(out, (byte[]) instanceObj); } else if (declClass.equals(Result[].class)) { Result.writeArray(out, (Result[]) instanceObj); } else { //if it is a Generic array, write the element's type if (getClassCode(declaredClass) == GENERIC_ARRAY_CODE) { Class<?> componentType = declaredClass.getComponentType(); writeClass(out, componentType); } int length = Array.getLength(instanceObj); out.writeInt(length); for (int i = 0; i < length; i++) { Object item = Array.get(instanceObj, i); writeObject(out, item, item.getClass(), conf); } } } else if (List.class.isAssignableFrom(declClass)) { List list = (List) instanceObj; int length = list.size(); out.writeInt(length); for (int i = 0; i < length; i++) { Object elem = list.get(i); writeObject(out, elem, elem == null ? Writable.class : elem.getClass(), conf); } } else if (declClass == String.class) { // String Text.writeString(out, (String) instanceObj); } else if (declClass.isPrimitive()) { // primitive type if (declClass == Boolean.TYPE) { // boolean out.writeBoolean(((Boolean) instanceObj).booleanValue()); } else if (declClass == Character.TYPE) { // char out.writeChar(((Character) instanceObj).charValue()); } else if (declClass == Byte.TYPE) { // byte out.writeByte(((Byte) instanceObj).byteValue()); } else if (declClass == Short.TYPE) { // short out.writeShort(((Short) instanceObj).shortValue()); } else if (declClass == Integer.TYPE) { // int out.writeInt(((Integer) instanceObj).intValue()); } else if (declClass == Long.TYPE) { // long out.writeLong(((Long) instanceObj).longValue()); } else if (declClass == Float.TYPE) { // float out.writeFloat(((Float) instanceObj).floatValue()); } else if (declClass == Double.TYPE) { // double out.writeDouble(((Double) instanceObj).doubleValue()); } else if (declClass == Void.TYPE) { // void } else { throw new IllegalArgumentException("Not a primitive: " + declClass); } } else if (declClass.isEnum()) { // enum Text.writeString(out, ((Enum) instanceObj).name()); } else if (Message.class.isAssignableFrom(declaredClass)) { Text.writeString(out, instanceObj.getClass().getName()); ((Message) instance).writeDelimitedTo(DataOutputOutputStream.constructOutputStream(out)); } else if (Writable.class.isAssignableFrom(declClass)) { // Writable Class<?> c = instanceObj.getClass(); Integer code = CLASS_TO_CODE.get(c); if (code == null) { out.writeByte(NOT_ENCODED); Text.writeString(out, c.getName()); } else { writeClassCode(out, c); } ((Writable) instanceObj).write(out); } else if (Serializable.class.isAssignableFrom(declClass)) { Class<?> c = instanceObj.getClass(); Integer code = CLASS_TO_CODE.get(c); if (code == null) { out.writeByte(NOT_ENCODED); Text.writeString(out, c.getName()); } else { writeClassCode(out, c); } ByteArrayOutputStream bos = null; ObjectOutputStream oos = null; try { bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); oos.writeObject(instanceObj); byte[] value = bos.toByteArray(); out.writeInt(value.length); out.write(value); } finally { if (bos != null) bos.close(); if (oos != null) oos.close(); } } else { throw new IOException("Can't write: " + instanceObj + " as " + declClass); } }
From source file:org.apache.axis.utils.JavaUtils.java
/** Utility function to convert an Object to some desired Class. * * Right now this works for:/*from ww w .j ava2 s . co m*/ * arrays <-> Lists, * Holders <-> held values * @param arg the array to convert * @param destClass the actual class we want */ public static Object convert(Object arg, Class destClass) { if (destClass == null) { return arg; } Class argHeldType = null; if (arg != null) { argHeldType = getHolderValueType(arg.getClass()); } if (arg != null && argHeldType == null && destClass.isAssignableFrom(arg.getClass())) { return arg; } if (log.isDebugEnabled()) { String clsName = "null"; if (arg != null) clsName = arg.getClass().getName(); log.debug(Messages.getMessage("convert00", clsName, destClass.getName())); } // See if a previously converted value is stored in the argument. Object destValue = null; if (arg instanceof ConvertCache) { destValue = ((ConvertCache) arg).getConvertedValue(destClass); if (destValue != null) return destValue; } // Get the destination held type or the argument held type if they exist Class destHeldType = getHolderValueType(destClass); // Convert between Axis special purpose HexBinary and byte[] if (arg instanceof HexBinary && destClass == byte[].class) { return ((HexBinary) arg).getBytes(); } else if (arg instanceof byte[] && destClass == HexBinary.class) { return new HexBinary((byte[]) arg); } // Convert between Calendar and Date if (arg instanceof Calendar && destClass == Date.class) { return ((Calendar) arg).getTime(); } if (arg instanceof Date && destClass == Calendar.class) { Calendar calendar = Calendar.getInstance(); calendar.setTime((Date) arg); return calendar; } // Convert between Calendar and java.sql.Date if (arg instanceof Calendar && destClass == java.sql.Date.class) { return new java.sql.Date(((Calendar) arg).getTime().getTime()); } // Convert between HashMap and Hashtable if (arg instanceof HashMap && destClass == Hashtable.class) { return new Hashtable((HashMap) arg); } // Convert an AttachmentPart to the given destination class. if (isAttachmentSupported() && (arg instanceof InputStream || arg instanceof AttachmentPart || arg instanceof DataHandler)) { try { String destName = destClass.getName(); if (destClass == String.class || destClass == OctetStream.class || destClass == byte[].class || destClass == Image.class || destClass == Source.class || destClass == DataHandler.class || destName.equals("javax.mail.internet.MimeMultipart")) { DataHandler handler = null; if (arg instanceof AttachmentPart) { handler = ((AttachmentPart) arg).getDataHandler(); } else if (arg instanceof DataHandler) { handler = (DataHandler) arg; } if (destClass == Image.class) { // Note: An ImageIO component is required to process an Image // attachment, but if the image would be null // (is.available == 0) then ImageIO component isn't needed // and we can return null. InputStream is = handler.getInputStream(); if (is.available() == 0) { return null; } else { ImageIO imageIO = ImageIOFactory.getImageIO(); if (imageIO != null) { return getImageFromStream(is); } else { log.info(Messages.getMessage("needImageIO")); return arg; } } } else if (destClass == javax.xml.transform.Source.class) { // For a reason unknown to me, the handler's // content is a String. Convert it to a // StreamSource. return new StreamSource(handler.getInputStream()); } else if (destClass == OctetStream.class || destClass == byte[].class) { InputStream in = null; if (arg instanceof InputStream) { in = (InputStream) arg; } else { in = handler.getInputStream(); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); int byte1 = -1; while ((byte1 = in.read()) != -1) baos.write(byte1); return new OctetStream(baos.toByteArray()); } else if (destClass == DataHandler.class) { return handler; } else { return handler.getContent(); } } } catch (IOException ioe) { } catch (SOAPException se) { } } // If the destination is an array and the source // is a suitable component, return an array with // the single item. if (arg != null && destClass.isArray() && !destClass.getComponentType().equals(Object.class) && destClass.getComponentType().isAssignableFrom(arg.getClass())) { Object array = Array.newInstance(destClass.getComponentType(), 1); Array.set(array, 0, arg); return array; } // in case destClass is array and arg is ArrayOfT class. (ArrayOfT -> T[]) if (arg != null && destClass.isArray()) { Object newArg = ArrayUtil.convertObjectToArray(arg, destClass); if (newArg == null || (newArg != ArrayUtil.NON_CONVERTABLE && newArg != arg)) { return newArg; } } // in case arg is ArrayOfT and destClass is an array. (T[] -> ArrayOfT) if (arg != null && arg.getClass().isArray()) { Object newArg = ArrayUtil.convertArrayToObject(arg, destClass); if (newArg != null) return newArg; } // Return if no conversion is available if (!(arg instanceof Collection || (arg != null && arg.getClass().isArray())) && ((destHeldType == null && argHeldType == null) || (destHeldType != null && argHeldType != null))) { return arg; } // Take care of Holder conversion if (destHeldType != null) { // Convert arg into Holder holding arg. Object newArg = convert(arg, destHeldType); Object argHolder = null; try { argHolder = destClass.newInstance(); setHolderValue(argHolder, newArg); return argHolder; } catch (Exception e) { return arg; } } else if (argHeldType != null) { // Convert arg into the held type try { Object newArg = getHolderValue(arg); return convert(newArg, destClass); } catch (HolderException e) { return arg; } } // Flow to here indicates that neither arg or destClass is a Holder // Check to see if the argument has a prefered destination class. if (arg instanceof ConvertCache && ((ConvertCache) arg).getDestClass() != destClass) { Class hintClass = ((ConvertCache) arg).getDestClass(); if (hintClass != null && hintClass.isArray() && destClass.isArray() && destClass.isAssignableFrom(hintClass)) { destClass = hintClass; destValue = ((ConvertCache) arg).getConvertedValue(destClass); if (destValue != null) return destValue; } } if (arg == null) { return arg; } // The arg may be an array or List int length = 0; if (arg.getClass().isArray()) { length = Array.getLength(arg); } else { length = ((Collection) arg).size(); } if (destClass.isArray()) { if (destClass.getComponentType().isPrimitive()) { Object array = Array.newInstance(destClass.getComponentType(), length); // Assign array elements if (arg.getClass().isArray()) { for (int i = 0; i < length; i++) { Array.set(array, i, Array.get(arg, i)); } } else { int idx = 0; for (Iterator i = ((Collection) arg).iterator(); i.hasNext();) { Array.set(array, idx++, i.next()); } } destValue = array; } else { Object[] array; try { array = (Object[]) Array.newInstance(destClass.getComponentType(), length); } catch (Exception e) { return arg; } // Use convert to assign array elements. if (arg.getClass().isArray()) { for (int i = 0; i < length; i++) { array[i] = convert(Array.get(arg, i), destClass.getComponentType()); } } else { int idx = 0; for (Iterator i = ((Collection) arg).iterator(); i.hasNext();) { array[idx++] = convert(i.next(), destClass.getComponentType()); } } destValue = array; } } else if (Collection.class.isAssignableFrom(destClass)) { Collection newList = null; try { // if we are trying to create an interface, build something // that implements the interface if (destClass == Collection.class || destClass == List.class) { newList = new ArrayList(); } else if (destClass == Set.class) { newList = new HashSet(); } else { newList = (Collection) destClass.newInstance(); } } catch (Exception e) { // Couldn't build one for some reason... so forget it. return arg; } if (arg.getClass().isArray()) { for (int j = 0; j < length; j++) { newList.add(Array.get(arg, j)); } } else { for (Iterator j = ((Collection) arg).iterator(); j.hasNext();) { newList.add(j.next()); } } destValue = newList; } else { destValue = arg; } // Store the converted value in the argument if possible. if (arg instanceof ConvertCache) { ((ConvertCache) arg).setConvertedValue(destClass, destValue); } return destValue; }
From source file:com.taobao.adfs.util.Utilities.java
public static String deepToString(Object object) { if (object == null) { return "null"; } else if (object instanceof Throwable) { return getThrowableStackTrace((Throwable) object); } else if (object.getClass().isEnum()) { return object.toString(); } else if (object.getClass().isArray()) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(object.getClass().getSimpleName()); int length = Array.getLength(object); stringBuilder.insert(stringBuilder.length() - 1, Array.getLength(object)).append("{"); for (int i = 0; i < length; i++) { stringBuilder.append(deepToString(Array.get(object, i))); if (i < length - 1) stringBuilder.append(','); }//from w w w .j av a2 s .c om return stringBuilder.append("}").toString(); } else if (List.class.isAssignableFrom(object.getClass())) { List<?> listObject = ((List<?>) object); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(object.getClass().getSimpleName()).append('[').append(listObject.size()) .append(']'); stringBuilder.append("{"); for (Object subObject : listObject) { stringBuilder.append(deepToString(subObject)).append(','); } if (!listObject.isEmpty()) stringBuilder.deleteCharAt(stringBuilder.length() - 1); return stringBuilder.append('}').toString(); } else { try { Method toStringMethod = Invocation.getPublicMethod(object.getClass(), "toString"); if (toStringMethod.getDeclaringClass() == Object.class) return toStringByFields(object, false); } catch (Throwable t) { } try { return object.toString(); } catch (Throwable t) { return "FailToString"; } } }
From source file:com.xpfriend.fixture.cast.temp.ObjectValidatorBase.java
protected boolean canValidate(Object object) { if (object == null) { return false; }/*from w ww.j ava2 s. c om*/ if (object instanceof List<?>) { List<?> list = (List<?>) object; if (list.size() == 0) { return false; } return isValidatableObject(list.get(0)); } if (object.getClass().isArray()) { if (Array.getLength(object) == 0) { return false; } return isValidatableObject(Array.get(object, 0)); } return isValidatableObject(object); }