List of usage examples for java.lang.reflect Array getLength
@HotSpotIntrinsicCandidate public static native int getLength(Object array) throws IllegalArgumentException;
From source file:com.gwtjs.common.util.spring.ObjectUtils.java
/** * Convert the given array (which may be a primitive array) to an * object array (if necessary of primitive wrapper objects). * <p>A {@code null} source value will be converted to an * empty Object array.// w w w . j a va 2 s . c o m * @param source the (potentially primitive) array * @return the corresponding object array (never {@code null}) * @throws IllegalArgumentException if the parameter is not an array */ @SuppressWarnings("rawtypes") public static Object[] toObjectArray(Object source) { if (source instanceof Object[]) { return (Object[]) source; } if (source == null) { return new Object[0]; } if (!source.getClass().isArray()) { throw new IllegalArgumentException("Source is not an array: " + source); } int length = Array.getLength(source); if (length == 0) { return new Object[0]; } Class wrapperType = Array.get(source, 0).getClass(); Object[] newArray = (Object[]) Array.newInstance(wrapperType, length); for (int i = 0; i < length; i++) { newArray[i] = Array.get(source, i); } return newArray; }
From source file:adams.ml.Dataset.java
public void setMappingFromBaseData(String key, BaseData bd) { if (bd != null) { if (bd.isNumeric()) { setType(key, BaseData.Type.NUMERIC); } else if (bd.isDate()) { setType(key, BaseData.Type.DATE); } else if (bd.isTime()) { setType(key, BaseData.Type.TIME); } else if (bd.isArray()) { if (Array.getLength(bd.getData()) > 0) { Object ao = Array.get(bd.getData(), 0); if (BaseData.isNumeric(ao)) { setType(key, BaseData.Type.NUMERIC, Array.getLength(bd.getData())); } else { setType(key, BaseData.Type.STRING, Array.getLength(bd.getData())); }//www . j a v a 2s . c om } } else { setType(key, BaseData.Type.STRING); } } }
From source file:com.browseengine.bobo.serialize.JSONSerializer.java
private static void dumpObject(JSONArray jsonArray, Class type, Object array, int index) throws JSONSerializationException, JSONException { if (type.isPrimitive()) { jsonArray.put(String.valueOf(Array.get(array, index))); } else if (type == String.class) { String val = (String) Array.get(array, index); if (val != null) { jsonArray.put(val); }//ww w . ja v a 2 s.c om } else if (JSONSerializable.class.isAssignableFrom(type)) { JSONSerializable o = (JSONSerializable) Array.get(array, index); JSONObject jobj = serializeJSONObject(o); jsonArray.put(jobj); } else if (type.isArray() && array != null) { Class compType = type.getComponentType(); Object subArray = Array.get(array, index); int len = Array.getLength(subArray); JSONArray arr = new JSONArray(); for (int k = 0; k < len; ++k) { dumpObject(arr, compType, subArray, k); } jsonArray.put(arr); } }
From source file:com.g3net.tool.ObjectUtils.java
/** * Convert the given array (which may be a primitive array) to an * object array (if necessary of primitive wrapper objects). * <p>A <code>null</code> source value will be converted to an * empty Object array.//from w ww . j a va 2s . co m * @param source the (potentially primitive) array * @return the corresponding object array (never <code>null</code>) * @throws IllegalArgumentException if the parameter is not an array */ public static Object[] toObjectArray(Object source) { if (source instanceof Object[]) { return (Object[]) source; } if (source == null) { return new Object[0]; } if (!source.getClass().isArray()) { throw new IllegalArgumentException("Source is not an array: " + source); } int length = Array.getLength(source); if (length == 0) { return new Object[0]; } Class wrapperType = Array.get(source, 0).getClass(); Object[] newArray = (Object[]) Array.newInstance(wrapperType, length); for (int i = 0; i < length; i++) { newArray[i] = Array.get(source, i); } return newArray; }
From source file:foam.lib.json.Outputter.java
protected Boolean maybeOutputProperty(FObject fo, PropertyInfo prop, boolean includeComma) { if (mode_ == OutputterMode.NETWORK && prop.getNetworkTransient()) return false; if (mode_ == OutputterMode.STORAGE && prop.getStorageTransient()) return false; if (!outputDefaultValues_ && !prop.isSet(fo)) return false; Object value = prop.get(fo);// w w w .j av a2 s . co m if (value == null || (isArray(value) && Array.getLength(value) == 0)) { return false; } if (includeComma) writer_.append(","); outputProperty(fo, prop); return true; }
From source file:org.apache.axis2.jaxws.marshaller.impl.alt.MethodMarshallerUtils.java
/** * Returns the list of PDElements that need to be marshalled onto the wire * * @param marshalDesc/* w w w. j a v a2 s . c o m*/ * @param params ParameterDescription for this operation * @param sigArguments arguments * @param isInput indicates if input or output params(input args on client, * output args on server) * @param isDocLitWrapped * @param isRPC * @return PDElements */ static List<PDElement> getPDElements(MarshalServiceRuntimeDescription marshalDesc, ParameterDescription[] params, Object[] sigArguments, boolean isInput, boolean isDocLitWrapped, boolean isRPC) { List<PDElement> pdeList = new ArrayList<PDElement>(); int index = 0; for (int i = 0; i < params.length; i++) { ParameterDescription pd = params[i]; if (pd.getMode() == Mode.IN && isInput || pd.getMode() == Mode.INOUT || pd.getMode() == Mode.OUT && !isInput) { // Get the matching signature argument Object value = sigArguments[i]; // Don't consider async handlers, they are are not represented on the wire, // thus they don't have a PDElement if (isAsyncHandler(value)) { continue; } // Convert from Holder into value if (isHolder(value)) { value = ((Holder) value).value; } // Get the formal type representing the value Class formalType = pd.getParameterActualType(); // The namespace and local name are obtained differently depending on // the style/use and header QName qName = null; if (pd.isHeader()) { // Headers (even rpc) are marshalled with the name defined by the // element= attribute on the wsd:part qName = new QName(pd.getTargetNamespace(), pd.getParameterName()); } else if (isDocLitWrapped) { // For doc/lit wrapped, the localName comes from the PartName qName = new QName(pd.getTargetNamespace(), pd.getPartName()); } else if (isRPC) { // Per WSI-BP, the namespace uri is unqualified qName = new QName(pd.getPartName()); } else { qName = new QName(pd.getTargetNamespace(), pd.getParameterName()); } // Create an Element rendering Element element = null; AttachmentDescription attachmentDesc = pd.getAttachmentDescription(); if (attachmentDesc != null) { PDElement pde = createPDElementForAttachment(pd, qName, value, formalType); pdeList.add(pde); } else { if (!marshalDesc.getAnnotationDesc(formalType).hasXmlRootElement()) { /* when a schema defines a SimpleType with xsd list jaxws tooling * generates artifacts with array rather than a java.util.List * However the ObjectFactory definition uses a List and thus * marshalling fails. Lets convert the Arrays to List and recreate * the JAXBElements for the same. */ if (pd.isListType()) { List<Object> list = new ArrayList<Object>(); if (formalType.isArray()) { for (int count = 0; count < Array.getLength(value); count++) { Object obj = Array.get(value, count); list.add(obj); } } element = new Element(list, qName, List.class); } else { element = new Element(value, qName, formalType); } } else { element = new Element(value, qName); } // The object is now ready for marshalling PDElement pde = new PDElement(pd, element, null); pdeList.add(pde); } } } return pdeList; }
From source file:jp.terasoluna.fw.web.struts.form.ValidatorActionFormEx.java
/** * wCfbNXuv?peBl??B//from w w w . ja v a 2 s. co m * * @param name ??CfbNXtv?peB * @param index ??CfbNXu * @param value ?v?peBl */ @SuppressWarnings("unchecked") public void setIndexedValue(String name, int index, Object value) { if (log.isDebugEnabled()) { log.debug("set(" + name + ", " + index + ", " + value + ") called."); } Object prop = null; try { prop = BeanUtil.getBeanProperty(this, name); } catch (PropertyAccessException e) { // DynaValidatorActionFormExdl??A // O????s?B } if (prop == null) { throw new NullPointerException("No indexed value for '" + name + "[" + index + "]'"); } else if (prop.getClass().isArray()) { if (index < Array.getLength(prop)) { Array.set(prop, index, value); } else { // CfbNX`FbN ActionFormUtil.checkIndexLength(index); // ?VKz?? Object newArray = Array.newInstance(prop.getClass().getComponentType(), index + 1); // zR|?[lgRs?[ System.arraycopy(prop, 0, newArray, 0, Array.getLength(prop)); // R|?[lgZbg Array.set(newArray, index, value); // Q?Rs?[ prop = newArray; } try { BeanUtil.setBeanProperty(this, name, prop); } catch (PropertyAccessException e) { throw new IllegalArgumentException("Cannot set property for '" + name + "[" + index + "]'"); } } else if (prop instanceof List) { if (index < ((List) prop).size()) { ((List) prop).set(index, value); } else { // CfbNX`FbN ActionFormUtil.checkIndexLength(index); Object[] oldValues = ((List) prop).toArray(); Object[] newValues = (Object[]) Array.newInstance(oldValues.getClass().getComponentType(), index + 1); System.arraycopy(oldValues, 0, newValues, 0, oldValues.length); newValues[index] = value; ((List) prop).clear(); ((List) prop).addAll(Arrays.asList(newValues)); } try { BeanUtil.setBeanProperty(this, name, prop); } catch (PropertyAccessException e) { throw new IllegalArgumentException("Cannot set property for '" + name + "[" + index + "]'"); } } else { throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]'"); } }
From source file:org.apache.axis.encoding.ser.ArraySerializer.java
/** * Serialize an element that is an array. * @param name is the element name//from w w w. ja va 2 s. co m * @param attributes are the attributes...serialize is free to add more. * @param value is the value * @param context is the SerializationContext */ public void serialize(QName name, Attributes attributes, Object value, SerializationContext context) throws IOException { if (value == null) throw new IOException(Messages.getMessage("cantDoNullArray00")); MessageContext msgContext = context.getMessageContext(); SchemaVersion schema = SchemaVersion.SCHEMA_2001; SOAPConstants soap = SOAPConstants.SOAP11_CONSTANTS; boolean encoded = context.isEncoded(); if (msgContext != null) { schema = msgContext.getSchemaVersion(); soap = msgContext.getSOAPConstants(); } Class cls = value.getClass(); Collection list = null; if (!cls.isArray()) { if (!(value instanceof Collection)) { throw new IOException(Messages.getMessage("cantSerialize00", cls.getName())); } list = (Collection) value; } // Get the componentType of the array/list Class componentClass; if (list == null) { componentClass = cls.getComponentType(); } else { componentClass = Object.class; } // Get the QName of the componentType // if it wasn't passed in from the constructor QName componentTypeQName = this.componentType; // Check to see if componentType is also an array. // If so, set the componentType to the most nested non-array // componentType. Increase the dims string by "[]" // each time through the loop. // Note from Rich Scheuerle: // This won't handle Lists of Lists or // arrays of Lists....only arrays of arrays. String dims = ""; if (componentTypeQName != null) { // if we have a Type QName at this point, // this is because ArraySerializer has been instanciated with it TypeMapping tm = context.getTypeMapping(); SerializerFactory factory = (SerializerFactory) tm.getSerializer(componentClass, componentTypeQName); while (componentClass.isArray() && factory instanceof ArraySerializerFactory) { ArraySerializerFactory asf = (ArraySerializerFactory) factory; componentClass = componentClass.getComponentType(); QName componentType = null; if (asf.getComponentType() != null) { componentType = asf.getComponentType(); if (encoded) { componentTypeQName = componentType; } } // update factory with the new values factory = (SerializerFactory) tm.getSerializer(componentClass, componentType); if (soap == SOAPConstants.SOAP12_CONSTANTS) dims += "* "; else dims += "[]"; } } else { // compatibility mode while (componentClass.isArray()) { componentClass = componentClass.getComponentType(); if (soap == SOAPConstants.SOAP12_CONSTANTS) dims += "* "; else dims += "[]"; } } // Try the current XML type from the context if (componentTypeQName == null) { componentTypeQName = context.getCurrentXMLType(); if (componentTypeQName != null) { if ((componentTypeQName.equals(xmlType) || componentTypeQName.equals(Constants.XSD_ANYTYPE) || componentTypeQName.equals(soap.getArrayType()))) { componentTypeQName = null; } } } if (componentTypeQName == null) { componentTypeQName = context.getItemType(); } // Then check the type mapping for the class if (componentTypeQName == null) { componentTypeQName = context.getQNameForClass(componentClass); } // If still not found, look at the super classes if (componentTypeQName == null) { Class searchCls = componentClass; while (searchCls != null && componentTypeQName == null) { searchCls = searchCls.getSuperclass(); componentTypeQName = context.getQNameForClass(searchCls); } if (componentTypeQName != null) { componentClass = searchCls; } } // Still can't find it? Throw an error. if (componentTypeQName == null) { throw new IOException(Messages.getMessage("noType00", componentClass.getName())); } int len = (list == null) ? Array.getLength(value) : list.size(); String arrayType = ""; int dim2Len = -1; if (encoded) { if (soap == SOAPConstants.SOAP12_CONSTANTS) { arrayType = dims + len; } else { arrayType = dims + "[" + len + "]"; } // Discover whether array can be serialized directly as a two-dimensional // array (i.e. arrayType=int[2,3]) versus an array of arrays. // Benefits: // - Less text passed on the wire. // - Easier to read wire format // - Tests the deserialization of multi-dimensional arrays. // Drawbacks: // - Is not safe! It is possible that the arrays are multiply // referenced. Transforming into a 2-dim array will cause the // multi-referenced information to be lost. Plus there is no // way to determine whether the arrays are multi-referenced. // - .NET currently (Dec 2002) does not support 2D SOAP-encoded arrays // // OLD Comment as to why this was ENABLED: // It is necessary for // interoperability (echo2DStringArray). It is 'safe' for now // because Axis treats arrays as non multi-ref (see the note // in SerializationContext.isPrimitive(...) ) // More complicated processing is necessary for 3-dim arrays, etc. // // Axis 1.1 - December 2002 // Turned this OFF because Microsoft .NET can not deserialize // multi-dimensional SOAP-encoded arrays, and this interopability // is pretty high visibility. Make it a global configuration parameter: // <parameter name="enable2DArrayEncoding" value="true"/> (tomj) // // Check the message context to see if we should turn 2D processing ON // Default is OFF boolean enable2Dim = false; // Vidyanand : added this check if (msgContext != null) { enable2Dim = JavaUtils .isTrueExplicitly(msgContext.getProperty(AxisEngine.PROP_TWOD_ARRAY_ENCODING)); } if (enable2Dim && !dims.equals("")) { if (cls.isArray() && len > 0) { boolean okay = true; // Make sure all of the component arrays are the same size for (int i = 0; i < len && okay; i++) { Object elementValue = Array.get(value, i); if (elementValue == null) okay = false; else if (dim2Len < 0) { dim2Len = Array.getLength(elementValue); if (dim2Len <= 0) { okay = false; } } else if (dim2Len != Array.getLength(elementValue)) { okay = false; } } // Update the arrayType to use mult-dim array encoding if (okay) { dims = dims.substring(0, dims.length() - 2); if (soap == SOAPConstants.SOAP12_CONSTANTS) arrayType = dims + len + " " + dim2Len; else arrayType = dims + "[" + len + "," + dim2Len + "]"; } else { dim2Len = -1; } } } } // Need to distinguish if this is array processing for an // actual schema array or for a maxOccurs usage. // For the maxOccurs case, the currentXMLType of the context is // the same as the componentTypeQName. QName itemQName = context.getItemQName(); boolean maxOccursUsage = !encoded && itemQName == null && componentTypeQName.equals(context.getCurrentXMLType()); if (encoded) { AttributesImpl attrs; if (attributes == null) { attrs = new AttributesImpl(); } else if (attributes instanceof AttributesImpl) { attrs = (AttributesImpl) attributes; } else { attrs = new AttributesImpl(attributes); } String compType = context.attributeQName2String(componentTypeQName); if (attrs.getIndex(soap.getEncodingURI(), soap.getAttrItemType()) == -1) { String encprefix = context.getPrefixForURI(soap.getEncodingURI()); if (soap != SOAPConstants.SOAP12_CONSTANTS) { compType = compType + arrayType; attrs.addAttribute(soap.getEncodingURI(), soap.getAttrItemType(), encprefix + ":arrayType", "CDATA", compType); } else { attrs.addAttribute(soap.getEncodingURI(), soap.getAttrItemType(), encprefix + ":itemType", "CDATA", compType); attrs.addAttribute(soap.getEncodingURI(), "arraySize", encprefix + ":arraySize", "CDATA", arrayType); } } // Force type to be SOAP_ARRAY for all array serialization. // // There are two choices here: // Force the type to type=SOAP_ARRAY // Pros: More interop test successes. // Cons: Since we have specific type information it // is more correct to use it. Plus the specific // type information may be important on the // server side to disambiguate overloaded operations. // Use the specific type information: // Pros: The specific type information is more correct // and may be useful for operation overloading. // Cons: More interop test failures (as of 2/6/2002). // String qname = context.getPrefixForURI(schema.getXsiURI(), "xsi") + ":type"; QName soapArray; if (soap == SOAPConstants.SOAP12_CONSTANTS) { soapArray = Constants.SOAP_ARRAY12; } else { soapArray = Constants.SOAP_ARRAY; } int typeI = attrs.getIndex(schema.getXsiURI(), "type"); if (typeI != -1) { attrs.setAttribute(typeI, schema.getXsiURI(), "type", qname, "CDATA", context.qName2String(soapArray)); } else { attrs.addAttribute(schema.getXsiURI(), "type", qname, "CDATA", context.qName2String(soapArray)); } attributes = attrs; } // For the maxOccurs case, each item is named with the QName // we got in the arguments. For normal array case, we write an element with // that QName, and then serialize each item as <item> QName elementName = name; Attributes serializeAttr = attributes; if (!maxOccursUsage) { serializeAttr = null; // since we are putting them here context.startElement(name, attributes); if (itemQName != null) elementName = itemQName; else if (componentQName != null) elementName = componentQName; } if (dim2Len < 0) { // Normal case, serialize each array element if (list == null) { for (int index = 0; index < len; index++) { Object aValue = Array.get(value, index); // Serialize the element. context.serialize(elementName, (serializeAttr == null ? serializeAttr : new AttributesImpl(serializeAttr)), aValue, componentTypeQName, componentClass); // prefered type QName } } else { for (Iterator iterator = list.iterator(); iterator.hasNext();) { Object aValue = iterator.next(); // Serialize the element. context.serialize(elementName, (serializeAttr == null ? serializeAttr : new AttributesImpl(serializeAttr)), aValue, componentTypeQName, componentClass); // prefered type QName } } } else { // Serialize as a 2 dimensional array for (int index = 0; index < len; index++) { for (int index2 = 0; index2 < dim2Len; index2++) { Object aValue = Array.get(Array.get(value, index), index2); context.serialize(elementName, null, aValue, componentTypeQName, componentClass); } } } if (!maxOccursUsage) context.endElement(); }
From source file:es.caib.zkib.jxpath.util.ValueUtils.java
/** * Returns the index'th element of the supplied collection. * @param collection to read/* w ww. j a va 2 s . c o m*/ * @param index int * @return collection[index] */ public static Object getValue(Object collection, int index) { collection = getValue(collection); Object value = collection; if (collection != null) { if (collection.getClass().isArray()) { if (index < 0 || index >= Array.getLength(collection)) { return null; } value = Array.get(collection, index); } else if (collection instanceof List) { if (index < 0 || index >= ((List) collection).size()) { return null; } value = ((List) collection).get(index); } else if (collection instanceof Collection) { int i = 0; Iterator it = ((Collection) collection).iterator(); for (; i < index; i++) { it.next(); } if (it.hasNext()) { value = it.next(); } else { value = null; } } } return value; }
From source file:com.darkstar.beanCartography.utils.finder.Finder.java
/** * Process the bean context stack.//from ww w . j a va 2s . c o m * * @param stack stack of objects left to search * @param visited set of objects already searched */ protected void visit(Deque<BeanContext> stack, Set<BeanContext> visited) { BeanContext target = stack.pop(); if (target == null) return; if (visited.contains(target)) return; visited.add(target); // process this object and check the filters. if passed filter then run interceptors... filtersInterceptors.entrySet().stream().filter(entry -> entry.getKey().accept(target.getSource())) .forEach(entry -> entry.getValue().intercept(target.getSource())); // process this object's contained objects (i.e. see what we need to add to the stack)... if (NameUtils.isImmutable(target.getSource().getClass())) return; Object fieldValue = null; try { while (target.hasNextFieldValue()) { fieldValue = target.nextFieldValue(); // skip nulls... if (fieldValue == null) continue; // add pojo or container or whatever this is... if (!visited.contains(fieldValue) && !stack.contains(fieldValue)) stack.add(new BeanContext(fieldValue)); // arrays... if (fieldValue.getClass().isArray()) { if (!processArrays) continue; final Object arrayFieldValue = fieldValue; IntStream.range(0, Array.getLength(arrayFieldValue)).forEach(i -> { Object element = Array.get(arrayFieldValue, i); if (element != null && !visited.contains(element) && !stack.contains(element)) stack.add(new BeanContext(element)); }); // collections... } else if (fieldValue instanceof Collection<?>) { if (!processCollections) continue; ((Collection<?>) fieldValue).stream().filter( element -> element != null && !visited.contains(element) && !stack.contains(element)) .forEach(element -> stack.add(new BeanContext(element))); // maps... } else if (fieldValue instanceof Map<?, ?>) { if (!processMaps) continue; ((Map<?, ?>) fieldValue).entrySet().stream().forEach(entry -> { if (entry.getKey() != null && !visited.contains(entry.getKey()) && !stack.contains(entry.getKey())) stack.add(new BeanContext(entry.getKey())); if (entry.getValue() != null && !visited.contains(entry.getValue()) && !stack.contains(entry.getValue())) stack.add(new BeanContext(entry.getValue())); }); } } } catch (Exception e) { e.printStackTrace(); } }