Java Code Examples for java.lang.reflect.Array#getLength()

The following examples show how to use java.lang.reflect.Array#getLength() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
@Override
public String toString() {
    if (userData == null) {
        return null;
    }
    if (userData.getClass().isArray()) {
        String name =
                Utils.getArrayClassName(userData.getClass().getName());
        int length = Array.getLength(userData);
        return name + "[" + length + "]";
    }

    if (userData instanceof CompositeData ||
            userData instanceof TabularData) {
        return userData.getClass().getName();
    }

    return userData.toString();
}
 
Example 2
Source Project: dubbox   File: Tool.java    License: Apache License 2.0 6 votes vote down vote up
public static int countMapValues(Map<?, ?> map) {
	int total = 0;
	if (map != null && map.size() > 0) {
 	for (Object value : map.values()) {
 		if (value != null) {
  		if (value instanceof Number) {
  			total += ((Number)value).intValue();
  		} else if (value.getClass().isArray()) {
  			total += Array.getLength(value);
  		} else if (value instanceof Collection) {
  			total += ((Collection<?>)value).size();
  		} else if (value instanceof Map) {
  			total += ((Map<?, ?>)value).size();
  		} else {
  			total += 1;
  		}
 		}
 	}
	}
	return total;
}
 
Example 3
/**
 * Return the length of a multi-valued attribute or 1 if it is a single
 * attribute. If {@code v} is {@code null} return 0.
 * <p>
 * The implementation treats several common collections and arrays as
 * special cases for speed.</p>
 */

public Object length(Object v) {
    if ( v==null ) return 0;
    int i = 1;      // we have at least one of something. Iterator and arrays might be empty.
    if ( v instanceof Map) i = ((Map<?, ?>)v).size();
    else if ( v instanceof Collection) i = ((Collection<?>)v).size();
    else if ( v instanceof Object[] ) i = ((Object[])v).length;
    else if ( v.getClass().isArray() ) i = Array.getLength(v);
    else if ( v instanceof Iterable || v instanceof Iterator ) {
        Iterator<?> it = v instanceof Iterable? ((Iterable<?>)v).iterator() : (Iterator<?>)v;
        i =0;
        while ( it.hasNext() ) {
            it.next();
            i++;
        }
    }
    return i;
}
 
Example 4
Source Project: cxf   File: InjectionUtils.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static Object mergeCollectionsOrArrays(Object first, Object second, Type genericType) {
    if (first == null) {
        return second;
    } else if (first instanceof Collection) {
        Collection.class.cast(first).addAll((Collection<?>) second);
        return first;
    } else {
        int firstLen = Array.getLength(first);
        int secondLen = Array.getLength(second);
        Object mergedArray = Array.newInstance(InjectionUtils.getActualType(genericType),
                                                firstLen + secondLen);
        System.arraycopy(first, 0, mergedArray, 0, firstLen);
        System.arraycopy(second, 0, mergedArray, firstLen, secondLen);
        return mergedArray;
    }
}
 
Example 5
@SuppressWarnings("unused")
private static final boolean rangeCheck(Object array, Object index) {
    if(!(index instanceof Number)) {
        return false;
    }
    final Number n = (Number)index;
    final int intIndex = n.intValue();
    final double doubleValue = n.doubleValue();
    if(intIndex != doubleValue && !Double.isInfinite(doubleValue)) { // let infinite trigger IOOBE
        return false;
    }
    if(0 <= intIndex && intIndex < Array.getLength(array)) {
        return true;
    }
    throw new ArrayIndexOutOfBoundsException("Array index out of range: " + n);
}
 
Example 6
private static StringBuilder appendArray(StringBuilder sb, final Object elements, final Function<Object, String> printFn) {
    sb.append('{');

    int nElements = Array.getLength(elements);
    for (int i = 0; i < nElements; i++) {
        if (i > 0) {
            sb.append(',');
        }

        Object o = Array.get(elements, i);
        if (o == null) {
            sb.append("NULL");
        } else if (o instanceof byte[]) {
            sb.append(BlobConversions.fromBytes((byte[]) o));
        } else if (o.getClass().isArray()) {
            sb = appendArray(sb, o, printFn);
        } else {
            sb = appendEscaped(sb, printFn.apply(o));
        }
    }

    return sb.append('}');
}
 
Example 7
Source Project: thorntail   File: PropertySubstitute.java    License: Apache License 2.0 5 votes vote down vote up
@Override
    public void set(Object object, Object value) throws Exception {
        if (write != null) {
            if (!filler) {
                write.invoke(object, value);
            } else if (value != null) {
                if (value instanceof Collection<?>) {
                    Collection<?> collection = (Collection<?>) value;
                    for (Object val : collection) {
                        write.invoke(object, val);
                    }
                } else if (value instanceof Map<?, ?>) {
                    Map<?, ?> map = (Map<?, ?>) value;
                    for (Entry<?, ?> entry : map.entrySet()) {
                        write.invoke(object, entry.getKey(), entry.getValue());
                    }
                } else if (value.getClass().isArray()) { // TODO: maybe arrays
                                                         // need 2 fillers like
                                                         // SET(index, value)
                                                         // add ADD(value)
                    int len = Array.getLength(value);
                    for (int i = 0; i < len; i++) {
                        write.invoke(object, Array.get(value, i));
                    }
                }
            }
        } else if (field != null) {
            field.set(object, value);
        } else if (delegate != null) {
            delegate.set(object, value);
        } else {
            // Thorntail::BEGIN
/*
            log.warning("No setter/delegate for '" + getName() + "' on object " + object);
*/
            // Thorntail::END
        }
        // TODO: maybe throw YAMLException here
    }
 
Example 8
public void dump( PrintWriter out, String _label, int _top ) {
  int arrayLen = Array.getLength( array );
  out.write( "<table class='cfdump_table_array'>" );
  if ( arrayLen > 0 ) {
    out.write( "<th class='cfdump_th_array' colspan='2'>" );
    if ( _label.length() > 0 ) out.write( _label + " - " );
    out.write( "array</th>" );
    
    int max = ( _top < arrayLen ? _top : arrayLen );
    
	for ( int x=0; x < max; x++ ){
      out.write( "<tr><td class='cfdump_td_array'>" );
      out.write( (x+1) + "" );
      out.write( "</td><td class='cfdump_td_value'>" );

      cfData element = tagUtils.convertToCfData( Array.get( array, x ) );
      if ( ( element == null ) || ( element.getDataType() == cfData.CFNULLDATA ) )
        out.write( "[undefined array element]" );
      else
        element.dump(out,"",_top);  
      
      out.write( "</td></tr>" );
    }
  } else {
    out.write( "<th class='cfdump_th_array' colspan='2'>array [empty]</th>" );
  }
  out.write( "</table>" );
}
 
Example 9
Source Project: GVGAI_GYM   File: ArrayTypeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override public void write(JsonWriter out, Object array) throws IOException {
  if (array == null) {
    out.nullValue();
    return;
  }

  out.beginArray();
  for (int i = 0, length = Array.getLength(array); i < length; i++) {
    E value = (E) Array.get(array, i);
    componentTypeAdapter.write(out, value);
  }
  out.endArray();
}
 
Example 10
Source Project: coming   File: arja5_five_s.java    License: MIT License 5 votes vote down vote up
/**
 * Returns a copy of the given array of size 1 greater than the argument.
 * The last value of the array is left to the default value.
 *
 * @param array The array to copy, must not be <code>null</code>.
 * @param newArrayComponentType If <code>array</code> is <code>null</code>, create a
 * size 1 array of this type.
 * @return A new copy of the array of size 1 greater than the input.
 */
private static Object copyArrayGrow1(Object array, Class<?> newArrayComponentType) {
    if (array != null) {
        int arrayLength = Array.getLength(array);
        Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);
        System.arraycopy(array, 0, newArray, 0, arrayLength);
        return newArray;
    }
    return Array.newInstance(newArrayComponentType, 1);
}
 
Example 11
public void serializeBody(Object array, XMLSerializer target) throws SAXException, IOException, XMLStreamException {
    int len = Array.getLength(array);
    for( int i=0; i<len; i++ )  {
        Object item = Array.get(array,i);
        try {
            xducer.writeText(target,item,"arrayItem");
        } catch (AccessorException e) {
            target.reportError("arrayItem",e);
        }
    }
}
 
Example 12
Source Project: rice   File: Formatter.java    License: Educational Community License v2.0 5 votes vote down vote up
public static Object toObject(Object value) {
    if (!value.getClass().isArray())
        return value;

    Class type = value.getClass().getComponentType();
    if (Array.getLength(value) == 0)
        return null;
    if (!type.isPrimitive())
        return Array.get(value, 0);
    if (boolean.class.isAssignableFrom(type))
        return Array.getBoolean(value, 0);
    if (char.class.isAssignableFrom(type))
        return new Character(Array.getChar(value, 0));
    if (byte.class.isAssignableFrom(type))
        return new Byte(Array.getByte(value, 0));
    if (int.class.isAssignableFrom(type))
        return new Integer(Array.getInt(value, 0));
    if (long.class.isAssignableFrom(type))
        return new Long(Array.getLong(value, 0));
    if (short.class.isAssignableFrom(type))
        return new Short(Array.getShort(value, 0));
    if (double.class.isAssignableFrom(type))
        return new Double(Array.getDouble(value, 0));
    if (float.class.isAssignableFrom(type))
        return new Float(Array.getFloat(value, 0));

    return null;
}
 
Example 13
/** Check array dimensions.
 * @param expected expected dimension
 * @param array (may be null if expected is 0)
 * @throws IllegalArgumentException if the array dimension does not match the expected one
 */
private void checkDimension(final int expected, final Object array)
    throws IllegalArgumentException {
    int arrayDimension = (array == null) ? 0 : Array.getLength(array);
    if (arrayDimension != expected) {
        throw MathRuntimeException.createIllegalArgumentException(
              "dimension mismatch {0} != {1}", arrayDimension, expected);
    }
}
 
Example 14
Source Project: incubator-atlas   File: AtlasArrayType.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValidValueForUpdate(Object obj) {
    if (obj != null) {
        if (obj instanceof List || obj instanceof Set) {
            Collection objList = (Collection) obj;

            if (!isValidElementCount(objList.size())) {
                return false;
            }

            for (Object element : objList) {
                if (!elementType.isValidValueForUpdate(element)) {
                    return false;
                }
            }
        } else if (obj.getClass().isArray()) {
            int arrayLen = Array.getLength(obj);

            if (!isValidElementCount(arrayLen)) {
                return false;
            }

            for (int i = 0; i < arrayLen; i++) {
                if (!elementType.isValidValueForUpdate(Array.get(obj, i))) {
                    return false;
                }
            }
        } else {
            return false; // invalid type
        }
    }

    return true;
}
 
Example 15
Source Project: CC   File: RemoteParamUtil.java    License: Apache License 2.0 5 votes vote down vote up
ArrayParam(Object obj) {
    super(obj);
    length = Array.getLength(obj);
    for (int i = 0; i < length; i++) {
        params.add(convertParam(Array.get(obj, i)));
    }
}
 
Example 16
/**
 * Compute the size of the given object.
 * @param value The value
 * @return The size
 */
protected final int sizeOf(Object value) {
    if (value instanceof Collection) {
        return ((Collection) value).size();
    } else if (value instanceof Iterable) {
        int i = 0;
        for (Object ignored : ((Iterable) value)) {
            i++;
        }
        return i;
    } else if (value.getClass().isArray()) {
        return Array.getLength(value);
    }
    return 1;
}
 
Example 17
public ArrayIterator(Object array) {
    this.array = array;
    n = Array.getLength(array);
}
 
Example 18
Source Project: titan1withtp3.1   File: Geoshape.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Geoshape convert(Object value) {

    if(value instanceof Map) {
        return convertGeoJson(value);
    }

    if(value instanceof Collection) {
        value = convertCollection((Collection<Object>) value);
    }

    if (value.getClass().isArray() && (value.getClass().getComponentType().isPrimitive() ||
            Number.class.isAssignableFrom(value.getClass().getComponentType())) ) {
        Geoshape shape = null;
        int len= Array.getLength(value);
        double[] arr = new double[len];
        for (int i=0;i<len;i++) arr[i]=((Number)Array.get(value,i)).doubleValue();
        if (len==2) shape= point(arr[0],arr[1]);
        else if (len==3) shape= circle(arr[0],arr[1],arr[2]);
        else if (len==4) shape= box(arr[0],arr[1],arr[2],arr[3]);
        else throw new IllegalArgumentException("Expected 2-4 coordinates to create Geoshape, but given: " + value);
        return shape;
    } else if (value instanceof String) {
        String[] components=null;
        for (String delimiter : new String[]{",",";"}) {
            components = ((String)value).split(delimiter);
            if (components.length>=2 && components.length<=4) break;
            else components=null;
        }
        Preconditions.checkArgument(components!=null,"Could not parse coordinates from string: %s",value);
        double[] coords = new double[components.length];
        try {
            for (int i=0;i<components.length;i++) {
                coords[i]=Double.parseDouble(components[i]);
            }
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Could not parse coordinates from string: " + value, e);
        }
        return convert(coords);
    } else return null;
}
 
Example 19
public static Component loadArray(Object value) {
    Component comp = null;
    if (isViewableValue(value)) {
        Object[] arr;
        if (value instanceof Collection) {
            arr = ((Collection<?>) value).toArray();
        } else if (value instanceof Map) {
            arr = ((Map<?,?>) value).entrySet().toArray();
        } else if (value instanceof Object[]) {
            arr = (Object[]) value;
        } else {
            int length = Array.getLength(value);
            arr = new Object[length];
            for (int i = 0; i < length; i++) {
                arr[i] = Array.get(value, i);
            }
        }
        JEditorPane arrayEditor = new JEditorPane();
        arrayEditor.setContentType("text/html");
        arrayEditor.setEditable(false);
        Color evenRowColor = arrayEditor.getBackground();
        int red = evenRowColor.getRed();
        int green = evenRowColor.getGreen();
        int blue = evenRowColor.getBlue();
        String evenRowColorStr =
                "rgb(" + red + "," + green + "," + blue + ")";
        Color oddRowColor = new Color(
                red < 20 ? red + 20 : red - 20,
                green < 20 ? green + 20 : green - 20,
                blue < 20 ? blue + 20 : blue - 20);
        String oddRowColorStr =
                "rgb(" + oddRowColor.getRed() + "," +
                oddRowColor.getGreen() + "," +
                oddRowColor.getBlue() + ")";
        Color foreground = arrayEditor.getForeground();
        String textColor = String.format("%06x",
                                         foreground.getRGB() & 0xFFFFFF);
        StringBuilder sb = new StringBuilder();
        sb.append("<html><body text=#"+textColor+"><table width=\"100%\">");
        for (int i = 0; i < arr.length; i++) {
            if (i % 2 == 0) {
                sb.append("<tr style=\"background-color: " +
                        evenRowColorStr + "\"><td><pre>" +
                        (arr[i] == null ?
                            arr[i] : htmlize(arr[i].toString())) +
                        "</pre></td></tr>");
            } else {
                sb.append("<tr style=\"background-color: " +
                        oddRowColorStr + "\"><td><pre>" +
                        (arr[i] == null ?
                            arr[i] : htmlize(arr[i].toString())) +
                        "</pre></td></tr>");
            }
        }
        if (arr.length == 0) {
            sb.append("<tr style=\"background-color: " +
                    evenRowColorStr + "\"><td></td></tr>");
        }
        sb.append("</table></body></html>");
        arrayEditor.setText(sb.toString());
        JScrollPane scrollp = new JScrollPane(arrayEditor);
        comp = scrollp;
    }
    return comp;
}
 
Example 20
/**
 * This method is used to convert the provided value into an XML
 * usable format. This is used in the serialization process when
 * there is a need to convert a field value in to a string so 
 * that that value can be written as a valid XML entity.
 * 
 * @param value this is the value to be converted to a string
 * 
 * @return this is the string representation of the given value
 */
public String write(Object value) throws Exception {
   int length = Array.getLength(value);

   if(entry == char.class) {
      char[] array = (char[])value;
      return new String(array);
   }
   return write(value, length);      
}