List of usage examples for java.lang.reflect Array getLength
@HotSpotIntrinsicCandidate public static native int getLength(Object array) throws IllegalArgumentException;
From source file:javadz.beanutils.ConvertUtilsBean.java
/** * Convert the specified value into a String. If the specified value * is an array, the first element (converted to a String) will be * returned. The registered {@link Converter} for the * <code>java.lang.String</code> class will be used, which allows * applications to customize Object->String conversions (the default * implementation simply uses toString()). * * @param value Value to be converted (may be null) * @return The converted String value//w ww . j a v a2s . com */ public String convert(Object value) { if (value == null) { return null; } else if (value.getClass().isArray()) { if (Array.getLength(value) < 1) { return (null); } value = Array.get(value, 0); if (value == null) { return null; } else { Converter converter = lookup(String.class); return ((String) converter.convert(String.class, value)); } } else { Converter converter = lookup(String.class); return ((String) converter.convert(String.class, value)); } }
From source file:com.xpfriend.fixture.cast.temp.ObjectValidatorBase.java
protected String fromArrayToString(Object array) { StringBuilder sb = new StringBuilder(); int length = Array.getLength(array); for (int i = 0; i < length; i++) { if (i != 0) { sb.append('|'); }/*from w w w . j av a 2 s .c o m*/ sb.append(toString(Array.get(array, i))); } return sb.toString(); }
From source file:com.twinsoft.convertigo.beans.core.TransactionWithVariables.java
public Object getParameterValue(String parameterName) throws EngineException { Object variableValue = null;//from w w w . j a va2 s . c om int variableVisibility = getVariableVisibility(parameterName); // Transaction parameter variableValue = variables.get(parameterName); if (variableValue != null) Engine.logBeans.trace("(TransactionWithVariables) parameter value: " + Visibility.Logs.printValue(variableVisibility, variableValue)); // Otherwise context parameter if (variableValue == null && context != null) { variableValue = (context.get(parameterName) == null ? null : context.get(parameterName)); if (variableValue != null) Engine.logBeans.trace("(TransactionWithVariables) context value: " + Visibility.Logs.printValue(variableVisibility, variableValue)); } // Otherwise default transaction parameter value if (variableValue == null) { variableValue = getVariableValue(parameterName); if (variableValue != null) Engine.logBeans.trace("(TransactionWithVariables) default value: " + Visibility.Logs.printValue(variableVisibility, variableValue)); } if (variableValue == null) { Engine.logBeans.trace("(TransactionWithVariables) none value found"); } else if (variableValue.getClass().isArray()) { Engine.logBeans.trace("(TransactionWithVariables) transform the array value as a collection"); if (variableValue.getClass().getComponentType().isPrimitive()) { int len = Array.getLength(variableValue); Collection<Object> newVariableValue = new ArrayList<Object>(len); for (int i = 0; i < len; i++) { newVariableValue.add(Array.get(variableValue, i)); } variableValue = newVariableValue; } else { variableValue = Arrays.asList((Object[]) variableValue); } } return variableValue; }
From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java
public static Node writeObjectToXml(Document document, Object object, Object compiledValue) throws Exception { if (object == null) return null; if (object instanceof Enum) { object = ((Enum<?>) object).name(); }//from w w w . jav a 2 s . c o m // Simple objects if ((object instanceof Boolean) || (object instanceof Integer) || (object instanceof Double) || (object instanceof Float) || (object instanceof Character) || (object instanceof Long) || (object instanceof Short) || (object instanceof Byte)) { Element element = document.createElement(object.getClass().getName()); element.setAttribute("value", object.toString()); if (compiledValue != null) element.setAttribute("compiledValue", compiledValue.toString()); return element; } // Strings else if (object instanceof String) { Element element = document.createElement(object.getClass().getName()); element.setAttribute("value", object.toString()); if (compiledValue != null) { element.setAttribute("compiledValueClass", compiledValue.getClass().getCanonicalName()); element.setAttribute("compiledValue", compiledValue.toString()); } return element; } // Arrays else if (object.getClass().getName().startsWith("[")) { String arrayClassName = object.getClass().getName(); int i = arrayClassName.lastIndexOf('['); String itemClassName = arrayClassName.substring(i + 1); char c = itemClassName.charAt(itemClassName.length() - 1); switch (c) { case ';': itemClassName = itemClassName.substring(1, itemClassName.length() - 1); break; case 'B': itemClassName = "byte"; break; case 'C': itemClassName = "char"; break; case 'D': itemClassName = "double"; break; case 'F': itemClassName = "float"; break; case 'I': itemClassName = "int"; break; case 'J': itemClassName = "long"; break; case 'S': itemClassName = "short"; break; case 'Z': itemClassName = "boolean"; break; } Element element = document.createElement("array"); element.setAttribute("classname", itemClassName); int len = Array.getLength(object); element.setAttribute("length", Integer.toString(len)); Node subNode; for (int k = 0; k < len; k++) { subNode = writeObjectToXml(document, Array.get(object, k)); if (subNode != null) { element.appendChild(subNode); } } return element; } // XMLization else if (object instanceof XMLizable) { Element element = document.createElement("xmlizable"); element.setAttribute("classname", object.getClass().getName()); element.appendChild(((XMLizable) object).writeXml(document)); return element; } // Default serialization else { Element element = document.createElement("serializable"); element.setAttribute("classname", object.getClass().getName()); String objectBytesEncoded = null; byte[] objectBytes = null; // We write the object to a bytes array ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(object); objectOutputStream.flush(); outputStream.close(); // Now, we retrieve the object bytes objectBytes = outputStream.toByteArray(); objectBytesEncoded = org.apache.commons.codec.binary.Base64.encodeBase64String(objectBytes); CDATASection cDATASection = document.createCDATASection(new String(objectBytesEncoded)); element.appendChild(cDATASection); return element; } }
From source file:edu.umn.cs.spatialHadoop.nasa.StockQuadTree.java
/** * Constructs an aggregate quad tree out of a two-dimensional array of values. * /*w w w .j a v a2s .c o m*/ * @param values * @param out * - the output stream to write the constructed quad tree to * @throws IOException */ public static void build(NASADataset metadata, short[] values, short fillValue, DataOutputStream out) throws IOException { int length = Array.getLength(values); int resolution = (int) Math.round(Math.sqrt(length)); // Write tree header out.writeInt(resolution); // resolution out.writeShort(fillValue); out.writeInt(1); // cardinality out.writeLong(metadata.time); // Timestamp // Fetch the stock quad tree of the associated resolution StockQuadTree stockQuadTree = getOrCreateStockQuadTree(resolution); // Sort values by their respective Z-Order values in linear time short[] sortedValues = new short[length]; for (int i = 0; i < length; i++) sortedValues[i] = values[stockQuadTree.r[i]]; // Write all sorted values for (short v : sortedValues) out.writeShort(v); // Compute aggregate values for all nodes in the tree // Go in reverse ID order to ensure children are computed before parents Node[] nodes = new Node[stockQuadTree.nodesID.length]; for (int iNode = stockQuadTree.nodesID.length - 1; iNode >= 0; iNode--) { // Initialize all aggregate values nodes[iNode] = new Node(); int firstChildId = stockQuadTree.nodesID[iNode] * 4; int firstChildPos = Arrays.binarySearch(stockQuadTree.nodesID, firstChildId); boolean isLeaf = firstChildPos < 0; if (isLeaf) { for (int iVal = stockQuadTree.nodesStartPosition[iNode]; iVal < stockQuadTree.nodesEndPosition[iNode]; iVal++) { short value; Object val = Array.get(sortedValues, iVal); if (val instanceof Short) { value = (Short) val; } else { throw new RuntimeException("Cannot handle values of type " + val.getClass()); } if (value != fillValue) nodes[iNode].accumulate(value); } } else { // Compute from the four children for (int iChild = 0; iChild < 4; iChild++) { int childPos = firstChildPos + iChild; nodes[iNode].accumulate(nodes[childPos]); } } } // Write nodes to file in sorted order for (int iNode = 0; iNode < nodes.length; iNode++) nodes[iNode].write(out); }
From source file:jef.tools.collection.CollectionUtils.java
/** * Enumation?Collection/* w w w . j a v a 2 s. co m*/ * * @param data * @param type * @return */ @SuppressWarnings("unchecked") public static <T> Collection<T> toCollection(Object data, Class<T> type) { if (data == null) return null; if (data instanceof Collection) { return ((Collection<T>) data); } else if (data.getClass().isArray()) { if (data.getClass().getComponentType().isPrimitive()) { int len = Array.getLength(data); List<T> result = new ArrayList<T>(len); for (int i = 0; i < len; i++) { result.add((T) Array.get(data, i)); } } else { return Arrays.asList((T[]) data); } } else if (data instanceof Enumeration) { Enumeration<T> e = (Enumeration<T>) data; List<T> result = new ArrayList<T>(); for (; e.hasMoreElements();) { result.add(e.nextElement()); } return result; } throw new IllegalArgumentException("The input type " + data.getClass() + " can not convert to Collection."); }
From source file:jp.terasoluna.fw.validation.ValidationUtil.java
/** * ??????<code>Collection</code>???? * ????????????/*from w w w . j ava 2 s . c om*/ * * ??<code>Collection</code>?<code>null</code>? * ????0????????????? * Collection???????IllegalArgumentException?? * * @param obj ??<code>Collection</code> * @param min ??? * @param max ?? * @return * ??<code>Collection</code>? * ???????? * <code>true</code>? * ?????<code>false</code>? */ public static boolean isArrayInRange(Object obj, int min, int max) { // ?? int targetLength = 0; if (obj == null) { targetLength = 0; } else if (obj instanceof Collection) { targetLength = ((Collection<?>) obj).size(); } else if (obj.getClass().isArray()) { targetLength = Array.getLength(obj); } else { // ????????IllegalArgumentException throw new IllegalArgumentException(obj.getClass().getName() + " is neither Array nor Collection."); } // ??????false? if (!GenericValidator.isInRange(targetLength, min, max)) { return false; } return true; }
From source file:com.astamuse.asta4d.web.form.flow.base.AbstractFormFlowSnippet.java
/** * Sub classes could override this method to customize how to handle the injection trace data for type unmatch errors. * //from w w w . ja va 2 s. c o m * @param fieldName * @param fieldDataType * @param rawTraceData * @return */ protected Object convertRawInjectionTraceDataToRenderingData(String fieldName, Class fieldDataType, Object rawTraceData) { if (fieldDataType.isArray() && rawTraceData.getClass().isArray()) { return rawTraceData; } else if (rawTraceData.getClass().isArray()) {// but field data type is // not array if (Array.getLength(rawTraceData) > 0) { return Array.get(rawTraceData, 0); } else { return null; } } else { return rawTraceData; } }
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 w w w. j ava 2 s .c o 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:org.apache.hadoop.hbase.security.access.HbaseObjectWritableFor96Migration.java
/** * Write a {@link Writable}, {@link String}, primitive type, or an array of * the preceding.//from ww w. j a v a2 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); } }