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

The following are Jave code examples for showing how to use getLength() of the java.lang.reflect.Array class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: openjdk-jdk10   File: XMBeanNotifications.java   View Source Code Vote up 6 votes
@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
Project: jDialects   File: ObjectUtils.java   View Source Code Vote up 6 votes
/**
 * 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.
 * @param source the (potentially primitive) array
 * @return the corresponding object array (never {@code null})
 * @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;
}
 
Example 3
Project: openjdk-jdk10   File: Test4058433.java   View Source Code Vote up 6 votes
private static void print(FeatureDescriptor descriptor) {
    String name = descriptor.getName();
    String display = descriptor.getDisplayName();
    String description = descriptor.getShortDescription();
    System.out.println("name: " + name);
    if (!Objects.equals(name, display)) {
        System.out.println("display name: " + display);
    }
    if (!Objects.equals(display, description)) {
        System.out.println("description: " + description.trim());
    }
    print("expert", descriptor.isExpert());
    print("hidden", descriptor.isHidden());
    print("preferred", descriptor.isPreferred());
    TreeMap<String,Object> map = new TreeMap<>();
    Enumeration<String> enumeration = descriptor.attributeNames();
    while (enumeration.hasMoreElements()) {
        String id = enumeration.nextElement();
        Object value = descriptor.getValue(id);
        if (value.getClass().isArray()) {
            TreeSet<String> set = new TreeSet<>();
            int index = 0;
            int length = Array.getLength(value);
            while (index < length) {
                set.add(Array.get(value, index++) + ", " +
                        Array.get(value, index++) + ", " +
                        Array.get(value, index++));
            }
            value = set.toString();
        }
        map.put(id, value);
    }
    for (Entry<String,Object> entry : map.entrySet()) {
        System.out.println(entry.getKey() + ": " + entry.getValue());
    }
}
 
Example 4
Project: uroborosql   File: ParenBindVariableNode.java   View Source Code Vote up 6 votes
/**
 * 配列の値をIN句として加工してバインドする
 *
 * @param transformContext transformコンテキスト
 * @param values バインドする値の配列
 */
private void bindArray(final TransformContext transformContext, final Object values) {
	int length = Array.getLength(values);
	if (length == 0) {
		throw new ParameterNotFoundRuntimeException("Parameter is not set. [" + expression + "]");
	}

	transformContext.addSqlPart("(?");
	transformContext.addBindVariable(Array.get(values, 0));
	for (int i = 1; i < length; i++) {
		transformContext.addSqlPart(", ?");
		transformContext.addBindVariable(Array.get(values, i));
	}
	transformContext.addSqlPart(")/*").addSqlPart(expression).addSqlPart("*/");
	transformContext.addBindName(expression);
}
 
Example 5
Project: lams   File: PersistentArrayHolder.java   View Source Code Vote up 5 votes
@Override
public Serializable disassemble(CollectionPersister persister) throws HibernateException {
	final int length = Array.getLength( array );
	final Serializable[] result = new Serializable[length];
	for ( int i=0; i<length; i++ ) {
		result[i] = persister.getElementType().disassemble( Array.get( array,i ), getSession(), null );
	}

	return result;
}
 
Example 6
Project: jsf-sdk   File: JSONPath.java   View Source Code Vote up 5 votes
@SuppressWarnings("rawtypes")
protected Object getArrayItem(final Object currentObject, int index) {
    if (currentObject == null) {
        return null;
    }

    if (currentObject instanceof List) {
        List list = (List) currentObject;

        if (index >= 0) {
            if (index < list.size()) {
                return list.get(index);
            }
            return null;
        } else {
            if (Math.abs(index) <= list.size()) {
                return list.get(list.size() + index);
            }
            return null;
        }
    }

    if (currentObject.getClass().isArray()) {
        int arrayLenth = Array.getLength(currentObject);

        if (index >= 0) {
            if (index < arrayLenth) {
                return Array.get(currentObject, index);
            }
            return null;
        } else {
            if (Math.abs(index) <= arrayLenth) {
                return Array.get(currentObject, arrayLenth + index);
            }
            return null;
        }
    }

    throw new UnsupportedOperationException();
}
 
Example 7
Project: retrofit-xmlrpc   File: MethodCall.java   View Source Code Vote up 5 votes
public static MethodCall create(String method, Object param) {
    MethodCall methodCall = new MethodCall();
    methodCall.methodName = method;

    if (param.getClass() == byte[].class) {
        methodCall.params = Collections.singletonList(Param.from(param));
    } else if (param.getClass().isArray()) {
        // Treat param as array of individual parameters
        int length = Array.getLength(param);
        methodCall.params = new ArrayList<>(length);
        for (int i = 0; i < length; i++) {
            methodCall.params.add(Param.from(Array.get(param, i)));
        }
    } else if (param instanceof Iterable) {
        // Treat param as collection of individual parameters
        Iterator iter = ((Iterable) param).iterator();
        methodCall.params = new ArrayList<>();
        while (iter.hasNext()) {
            methodCall.params.add(Param.from(iter.next()));
        }
    } else if (param instanceof Boolean || param instanceof Integer || param instanceof Long || param
            instanceof Double || param instanceof String) {
        methodCall.params = Collections.singletonList(Param.from(param));
    } else {
        // Treat param a an input object of which the fields represent the parameters
        Field[] fields = param.getClass().getDeclaredFields();
        methodCall.params = new ArrayList<>(fields.length);
        for (Field field : fields) {
            if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
                continue;
            }
            try {
                methodCall.params.add(Param.from(field.get(param)));
            } catch (IllegalAccessException e) {
                throw new RuntimeException(field.getName() + " could not be accessed to read XML-RPC param");
            }
        }
    }
    return methodCall;
}
 
Example 8
Project: tomcat7   File: JMXAccessorTask.java   View Source Code Vote up 5 votes
/**
 * @param name context of result
 * @param result
 */
protected void echoResult(String name, Object result) {
    if (isEcho()) {
        if (result.getClass().isArray()) {
            for (int i = 0; i < Array.getLength(result); i++) {
                handleOutput(name + "." + i + "=" + Array.get(result, i));
            }
        } else
            handleOutput(name + "=" + result);
    }
}
 
Example 9
Project: openjdk-jdk10   File: CatchExceptionTest.java   View Source Code Vote up 5 votes
private void assertEQ(T t, Object returned) {
    if (rtype.isArray()) {
        Asserts.assertEQ(t.getClass(), returned.getClass());
        int n = Array.getLength(t);
        Asserts.assertEQ(n, Array.getLength(returned));
        for (int i = 0; i < n; ++i) {
            Asserts.assertEQ(Array.get(t, i), Array.get(returned, i));
        }
    } else {
        Asserts.assertEQ(t, returned);
    }
}
 
Example 10
Project: hadoop-oss   File: JMXJsonServlet.java   View Source Code Vote up 5 votes
private void writeObject(JsonGenerator jg, Object value) throws IOException {
  if(value == null) {
    jg.writeNull();
  } else {
    Class<?> c = value.getClass();
    if (c.isArray()) {
      jg.writeStartArray();
      int len = Array.getLength(value);
      for (int j = 0; j < len; j++) {
        Object item = Array.get(value, j);
        writeObject(jg, item);
      }
      jg.writeEndArray();
    } else if(value instanceof Number) {
      Number n = (Number)value;
      jg.writeNumber(n.toString());
    } else if(value instanceof Boolean) {
      Boolean b = (Boolean)value;
      jg.writeBoolean(b);
    } else if(value instanceof CompositeData) {
      CompositeData cds = (CompositeData)value;
      CompositeType comp = cds.getCompositeType();
      Set<String> keys = comp.keySet();
      jg.writeStartObject();
      for(String key: keys) {
        writeAttribute(jg, key, cds.get(key));
      }
      jg.writeEndObject();
    } else if(value instanceof TabularData) {
      TabularData tds = (TabularData)value;
      jg.writeStartArray();
      for(Object entry : tds.values()) {
        writeObject(jg, entry);
      }
      jg.writeEndArray();
    } else {
      jg.writeString(value.toString());
    }
  }
}
 
Example 11
Project: allure-java   File: Allure1Utils.java   View Source Code Vote up 5 votes
/**
 * {@link Arrays#toString(Object[])} with {@link Arrays#toString(Object[])} for array elements.
 */
public static Object arrayToString(final Object obj) {
    if (obj != null && obj.getClass().isArray()) {
        final int len = Array.getLength(obj);
        final String[] strings = new String[len];
        for (int i = 0; i < len; i++) {
            strings[i] = String.valueOf(Array.get(obj, i));
        }
        return Arrays.toString(strings);
    } else {
        return obj;
    }
}
 
Example 12
Project: parabuild-ci   File: ArrayHolder.java   View Source Code Vote up 5 votes
/**
 * @see PersistentCollection#entries
 */
public Iterator elements() {
	//if (array==null) return tempList.iterator();
	int length = Array.getLength(array);
	java.util.List list = new ArrayList(length);
	for (int i=0; i<length; i++) {
		list.add( Array.get(array, i) );
	}
	return list.iterator();
}
 
Example 13
Project: xproject   File: ValidationAssert.java   View Source Code Vote up 5 votes
private static boolean isEmptyObject(Object object){
	if(object == null){
		return true;
	}else if(object instanceof String){
		return ((String)object).trim().equals("") || ((String)object).trim().equals("null");
	}else if(object instanceof Collection<?>){
		return ((Collection<?>)object).isEmpty();
	}else if(object instanceof Map<?,?>){
		return ((Map<?,?>)object).isEmpty();
	}else if(object.getClass().isArray()){
		return Array.getLength(object) == 0;
	}else{
		return false;
	}
}
 
Example 14
Project: openjdk-jdk10   File: AllocateUninitializedArray.java   View Source Code Vote up 5 votes
public static void testOK(Class<?> expectClass, int expectLen, Callable<Object> test) throws Exception {
    for (int c = 0; c < ITERS; c++) {
        Object res = test.call();
        Class<?> actualClass = res.getClass();
        if (!actualClass.equals(expectClass)) {
            throw new IllegalStateException("Wrong class: expected = " + expectClass + ", but got " + actualClass);
        }
        int actualLen = Array.getLength(res);
        if (actualLen != expectLen) {
            throw new IllegalStateException("Wrong length: expected = " + expectLen + ", but got " + actualLen);
        }
    }
}
 
Example 15
Project: GitHub   File: JSONArray.java   View Source Code Vote up 5 votes
/**
 * Construct a JSONArray from an array
 *
 * @throws JSONException
 *             If not an array.
 */
public JSONArray(Object array) throws JSONException {
    this();
    if (array.getClass().isArray()) {
        int length = Array.getLength(array);
        for (int i = 0; i < length; i += 1) {
            this.put(JSONObject.wrap(Array.get(array, i)));
        }
    } else {
        throw new JSONException(
                "JSONArray initial value should be a string or collection or array.");
    }
}
 
Example 16
Project: OpenDiabetes   File: ArrayUtil.java   View Source Code Vote up 5 votes
/**
 * Returns a new array of given size, containing as many elements of
 * the original array as it can hold. N.B. Always returns a new array
 * even if newsize parameter is the same as the old size.
 */
public static Object resizeArray(Object source, int newsize) {

    Object newarray =
        Array.newInstance(source.getClass().getComponentType(), newsize);
    int oldsize = Array.getLength(source);

    if (oldsize < newsize) {
        newsize = oldsize;
    }

    System.arraycopy(source, 0, newarray, 0, newsize);

    return newarray;
}
 
Example 17
Project: monarch   File: MTableUtils.java   View Source Code Vote up 4 votes
/**
 * Return the deep hash-code of the object. If the object is an the hash-code is derived from each
 * element in the array, recursively, so that it is always consistent. For primitive objects
 * (int/long) or map it is direct hash code.
 * 
 * @param object the object of which hash-code is to be returned
 * @return the hash-code of the provided object
 */
public static int getDeepHashCode(final Object object) {
  int result;
  if (object == null) {
    result = 0;
  } else if (object instanceof byte[]) {
    result = Arrays.hashCode((byte[]) object);
  } else if (object instanceof short[]) {
    result = Arrays.hashCode((short[]) object);
  } else if (object instanceof int[]) {
    result = Arrays.hashCode((int[]) object);
  } else if (object instanceof long[]) {
    result = Arrays.hashCode((long[]) object);
  } else if (object instanceof char[]) {
    result = Arrays.hashCode((char[]) object);
  } else if (object instanceof float[]) {
    result = Arrays.hashCode((float[]) object);
  } else if (object instanceof double[]) {
    result = Arrays.hashCode((double[]) object);
  } else if (object instanceof boolean[]) {
    result = Arrays.hashCode((boolean[]) object);
  } else if (object instanceof Object[] || object.getClass().isArray()) {
    int len = Array.getLength(object);
    Object element;
    result = 1;
    for (int i = 0; i < len; i++) {
      element = Array.get(object, i);
      result = 31 * result + (element == null ? 0
          : (element instanceof Object[] || element.getClass().isArray()
              ? getDeepHashCode(element) : element.hashCode()));
    }
  } else if (object instanceof Map) {
    result = 0;
    for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) object).entrySet()) {
      result += (MTableUtils.getDeepHashCode(entry.getKey())
          ^ MTableUtils.getDeepHashCode(entry.getValue()));
    }
  } else {
    result = object.hashCode();
  }
  return result;
}
 
Example 18
Project: jdk8u-jdk   File: XArrayDataViewer.java   View Source Code Vote up 4 votes
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 19
Project: ats-framework   File: DbRecordValue.java   View Source Code Vote up 4 votes
public String getValueAsString() {

        // handle null value
        if (value == null) {
            return null;
        }

        // handle array
        if (value.getClass().isArray()) {
            StringBuilder valueAsString = new StringBuilder();

            valueAsString.append("[ ");
            for (int i = 0; i < Array.getLength(value); i++) {
                valueAsString.append(Array.get(value, i));
                valueAsString.append(", ");
            }

            if (valueAsString.toString().endsWith(", ")) {
                valueAsString.delete(valueAsString.length() - 2, valueAsString.length());
            }

            valueAsString.append(" ]");

            return valueAsString.toString();
        }

        if (oracleJdbcDriverInClassPath) {
            // handle oracle time stamp
            if (value instanceof oracle.sql.TIMESTAMP) {
                try {
                    return ((oracle.sql.TIMESTAMP) value).toJdbc().toString();
                } catch (SQLException e) {
                    // If get here, it is likely to break some functionality like Database Snapshots.
                    // Then we will have to revise this logic.
                    log.warn("There was error while parsing value as oracle.sql.TIMESTAMP."
                             + "We will instead return the value as " + value.toString() + " .", e);
                    return value.toString();
                }
            }
        }

        return value.toString();
    }
 
Example 20
Project: lams   File: PersistentArrayHolder.java   View Source Code Vote up 4 votes
@Override
public boolean needsInserting(Object entry, int i, Type elemType) throws HibernateException {
	final Serializable sn = getSnapshot();
	return Array.get( array, i ) != null && ( i >= Array.getLength( sn ) || Array.get( sn, i ) == null );
}