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

The following are Jave code examples for showing how to use get() 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: springbootWeb   File: HashCodeUtil.java   View Source Code Vote up 6 votes
/**
 * <code>aObject</code> is a possibly-null object field, and possibly an array.
 * 
 * If <code>aObject</code> is an array, then each element may be a primitive or a possibly-null object.
 *
 * @param aSeed
 *            the a seed
 * @param aObject
 *            the a object
 * @return the int
 */
public static int hash(int aSeed, Object aObject) {
    int result = aSeed;
    if (aObject == null) {
        result = hash(result, 0);
    } else if (!isArray(aObject)) {
        result = hash(result, aObject.hashCode());
    } else {
        int length = Array.getLength(aObject);
        for (int idx = 0; idx < length; ++idx) {
            Object item = Array.get(aObject, idx);
            // recursive call!
            result = hash(result, item);
        }
    }
    return result;
}
 
Example 2
Project: jdk8u-jdk   File: BasicAttribute.java   View Source Code Vote up 6 votes
/**
 * Determines whether two arrays are equal by comparing each of their
 * elements using <tt>Object.equals()</tt>.
 */
private static boolean arrayEquals(Object a1, Object a2) {
    int len;
    if ((len = Array.getLength(a1)) != Array.getLength(a2))
        return false;

    for (int j = 0; j < len; j++) {
        Object i1 = Array.get(a1, j);
        Object i2 = Array.get(a2, j);
        if (i1 == null || i2 == null) {
            if (i1 != i2)
                return false;
        } else if (!i1.equals(i2)) {
            return false;
        }
    }
    return true;
}
 
Example 3
Project: pandionj   File: MatrixWidget.java   View Source Code Vote up 6 votes
public MatrixFigure(IArrayModel<?> model) {
	this.model = model;
	org.eclipse.draw2d.GridLayout layout;
	Object array = model.getValues();
	int nLines = Array.getLength(array);
	if(nLines == 0) {
		layout = new org.eclipse.draw2d.GridLayout(1,true);
	}
	else {
		Object firstLine = Array.get(array, 0);
		layout = new org.eclipse.draw2d.GridLayout(Array.getLength(firstLine), true);
	}
	layout.horizontalSpacing = 20;
	layout.marginWidth = 10;
	setLayoutManager(layout);

	model.registerDisplayObserver((a) -> update());
	update();
}
 
Example 4
Project: beaker-notebook-archive   File: BasicObjectSerializer.java   View Source Code Vote up 5 votes
@Override
public boolean writeObject(Object obj, JsonGenerator jgen, boolean expand) throws JsonProcessingException, IOException {
  logger.debug("array");
  // write out an array of objects.
  jgen.writeStartArray();
  final int length = Array.getLength(obj);
  for (int i = 0; i < length; ++i) {
    Object o = Array.get(obj, i);
    if (!parent.writeObject(o, jgen, false)) {
        jgen.writeObject(o.toString());
    }
  }
  jgen.writeEndArray();
  return true;
}
 
Example 5
Project: ExPetrum   File: OreDictManager.java   View Source Code Vote up 5 votes
private static void processField(Field f)
{
	try
	{
		if (f.getType().isArray())
		{
			Object o = f.get(null);
			for (int i = 0; i < Array.getLength(o); ++i)
			{
				Object arrayAt = Array.get(o, i);
				if (IOreDictEntry.class.isAssignableFrom(arrayAt.getClass()))
				{
					((IOreDictEntry)arrayAt).registerOreDictNames();
				}
			}
		}
		else
		{
			Object at = f.get(null);
			if (at != null && IOreDictEntry.class.isAssignableFrom(at.getClass()))
			{
				((IOreDictEntry)f.get(null)).registerOreDictNames();
			}
		}
	}
	catch (Exception ex)
	{
		ex.printStackTrace();
	}
}
 
Example 6
Project: ats-framework   File: Validator.java   View Source Code Vote up 5 votes
/** Logs the signature of the method used for debuging purposes */
private void logMethodSignature( Stack<String> methodNames, Object[] argumentsValues ) {

    StringBuffer buffer = new StringBuffer();
    buffer.append(methodNames.peek()).append("( ");

    for (int i = 0; i < argumentsValues.length; i++) {
        if (argumentsValues[i] == null) {
            buffer.append("null");
        } else {
            if (argumentsValues[i].getClass().isArray()) {
                // we have an array, so get all elements
                buffer.append("{ ");

                for (int j = 0; j < Array.getLength(argumentsValues[i]); j++) {
                    if (Array.get(argumentsValues[i], j) == null) {
                        buffer.append("null");
                    } else {
                        buffer.append(Array.get(argumentsValues[i], j).toString());
                    }
                    if ( (j + 1) != Array.getLength(argumentsValues[i])) {
                        buffer.append(" , ");
                    }
                }

                buffer.append(" }");

            } else {
                buffer.append(argumentsValues[i].toString());
            }
        }
        if ( (i + 1) != argumentsValues.length) {
            buffer.append(" , ");
        }
    }
    buffer.append(" )");

    log.debug("START - " + buffer);
}
 
Example 7
Project: HCFCore   File: ArrayIterator.java   View Source Code Vote up 5 votes
/**
 * Returns the next element in the array.
 *
 * @return the next element in the array
 * @throws NoSuchElementException if all the elements in the array
 *  have already been returned
 */
@SuppressWarnings("unchecked")
public E next() {
    if (hasNext() == false) {
        throw new NoSuchElementException();
    }
    return (E) Array.get(array, index++);
}
 
Example 8
Project: VASSAL-src   File: CollectionManager.java   View Source Code Vote up 5 votes
/**
 * Create an enumeration over the given object
 *
 * @param iterateOverMe Object of type Enumeration, Vector, String, 
 *                      StringBuffer or an array
 *
 * @return an enumeration
 *
 * @throws java.lang.IllegalArgumentException If the argument is not a
 * supported (i.e. iterable) type.
 *
 * @throws java.lang.NullPointerException If the argument is null
 */
protected Enumeration createEnumeration( Object iterateOverMe )
{
	if(iterateOverMe==null)
		throw new NullPointerException("Object arguments passed to " +
			"the BasicBshIterator constructor cannot be null.");

	if (iterateOverMe instanceof Enumeration)
		return (Enumeration)iterateOverMe;

	if (iterateOverMe instanceof Vector)
		return ((Vector)iterateOverMe).elements();

	if (iterateOverMe.getClass().isArray()) {
		final Object array = iterateOverMe;
		return new Enumeration() {
			int index = 0, length = Array.getLength(array);
			public Object nextElement() { 
				return Array.get(array, index++);
			}
			public boolean hasMoreElements() { return index<length; }
		};
	} 
	
	if (iterateOverMe instanceof String)
		return createEnumeration(((String)iterateOverMe).toCharArray());
	
	if (iterateOverMe instanceof StringBuffer)
		return createEnumeration(
			iterateOverMe.toString().toCharArray());

	throw new IllegalArgumentException(
		"Cannot enumerate object of type "+iterateOverMe.getClass());
}
 
Example 9
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 10
Project: jdk8u-jdk   File: MXBeanTest.java   View Source Code Vote up 5 votes
private static String deepToString(Object o) {
    StringBuffer buf = new StringBuffer();
    buf.append("[");
    int len = Array.getLength(o);
    for (int i = 0; i < len; i++) {
        if (i > 0)
            buf.append(", ");
        Object e = Array.get(o, i);
        buf.append(string(e));
    }
    buf.append("]");
    return buf.toString();
}
 
Example 11
Project: marathonv5   File: RComponent.java   View Source Code Vote up 5 votes
public static Object unboxPremitiveArray(Object r) {
    int length = Array.getLength(r);
    ArrayList<Object> list = new ArrayList<Object>();
    for (int i = 0; i < length; i++) {
        Object e = Array.get(r, i);
        if (e != null && e.getClass().isArray()) {
            list.add(unboxPremitiveArray(e));
        } else {
            list.add(e);
        }
    }
    return list;
}
 
Example 12
Project: sucok-framework   File: Between.java   View Source Code Vote up 5 votes
@Override
public Criteria buildMongoCriteria(Object expression) {
	String path = expression.toString();
	Object value1 = Array.get(value, 0);
	Object value2 = Array.get(value, 1);
	return Criteria.where(path).gte(value1).and(path).lte(value2);
}
 
Example 13
Project: qpp-conversion-tool   File: MetadataTest.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
private static <T> T getDefaultValue(Class<T> clazz) {
	T defaultValue = null;

	try {
		defaultValue = clazz.getConstructor().newInstance();
	}
	catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
		defaultValue = (T) Array.get(Array.newInstance(clazz, 1), 0);
	}

	return defaultValue;
}
 
Example 14
Project: parabuild-ci   File: ToStringBean.java   View Source Code Vote up 5 votes
private void printArrayProperty(StringBuffer sb, String prefix,Object array) {
    int length = Array.getLength(array);
    for (int i=0;i<length;i++) {
        Object obj = Array.get(array,i);
        printProperty(sb,prefix+"["+i+"]",obj);
    }
}
 
Example 15
Project: flow-platform   File: ArrayAdaptor.java   View Source Code Vote up 5 votes
@Override
public Object write(Object array) {
    List<Object> objects = new ArrayList<>();

    for (int i = 0, length = Array.getLength(array); i < length; i++) {
        E value = (E) Array.get(array, i);
        objects.add(baseAdaptor.write(value));
    }

    return objects;
}
 
Example 16
Project: fintx-common   File: Arrays.java   View Source Code Vote up 5 votes
/**
 * Swaps a series of elements in the given array.
 *
 * <p>
 * This method does nothing for a {@code null} or empty input array or for overflow indices. Negative indices are promoted to 0(zero). If any of the
 * sub-arrays to swap falls outside of the given array, then the swap is stopped at the end of the array and as many as possible elements are swapped.
 * </p>
 *
 * Examples:
 * <ul>
 * <li>org.fintx.Arrays.swap(["1", "2", "3", "4"], 0, 2, 1) -&gt; ["3", "2", "1", "4"]</li>
 * <li>org.fintx.Arrays.swap(["1", "2", "3", "4"], 0, 0, 1) -&gt; ["1", "2", "3", "4"]</li>
 * <li>org.fintx.Arrays.swap(["1", "2", "3", "4"], 2, 0, 2) -&gt; ["3", "4", "1", "2"]</li>
 * <li>org.fintx.Arrays.swap(["1", "2", "3", "4"], -3, 2, 2) -&gt; ["3", "4", "1", "2"]</li>
 * <li>org.fintx.Arrays.swap(["1", "2", "3", "4"], 0, 3, 3) -&gt; ["4", "2", "3", "1"]</li>
 * </ul>
 * 
 * @param <T> the type of array eg:String[]
 * @param array the array to swap, may be {@code null}
 * @param offset1 the index of the first element in the series to swap
 * @param offset2 the index of the second element in the series to swap
 * @param len the number of elements to swap starting with the given indices
 */
public static <T> void swap(final T array, int offset1, int offset2, int len) {
    if (array == null) {
        return;
    }
    if (!array.getClass().isArray()) {
        throw new IllegalArgumentException("Argument array is not a Array!");
    }
    int length = getLength(array);
    if (array == null || length == 0 || offset1 >= length || offset2 >= length) {
        return;
    }
    if (!array.getClass().isArray()) {
        throw new IllegalArgumentException("Argument array is not a Array!");
    }
    if (offset1 < 0) {
        offset1 = 0;
    }
    if (offset2 < 0) {
        offset2 = 0;
    }
    len = Math.min(Math.min(len, length - offset1), length - offset2);
    Object aux = null;
    for (int i = 0; i < len; i++, offset1++, offset2++) {
        aux = Array.get(array, offset1);
        Array.set(array, offset1, Array.get(array, offset2));
        Array.set(array, offset2, aux);
    }
}
 
Example 17
Project: NotifyTools   File: ArrayConverter.java   View Source Code Vote up 4 votes
/**
 * Handles conversion to an array of the specified type.
 *
 * @param <T> Target type of the conversion.
 * @param type The type to which this value should be converted.
 * @param value The input value to be converted.
 * @return The converted value.
 * @throws Throwable if an error occurs converting to the specified type
 */
@Override
protected <T> T convertToType(final Class<T> type, final Object value) throws Throwable {

    if (!type.isArray()) {
        throw new ConversionException(toString(getClass())
                + " cannot handle conversion to '"
                + toString(type) + "' (not an array).");
    }

    // Handle the source
    int size = 0;
    Iterator<?> iterator = null;
    if (value.getClass().isArray()) {
        size = Array.getLength(value);
    } else {
        final Collection<?> collection = convertToCollection(type, value);
        size = collection.size();
        iterator = collection.iterator();
    }

    // Allocate a new Array
    final Class<?> componentType = type.getComponentType();
    final Object newArray = Array.newInstance(componentType, size);

    // Convert and set each element in the new Array
    for (int i = 0; i < size; i++) {
        Object element = iterator == null ? Array.get(value, i) : iterator.next();
        // TODO - probably should catch conversion errors and throw
        //        new exception providing better info back to the user
        element = elementConverter.convert(componentType, element);
        Array.set(newArray, i, element);
    }

    @SuppressWarnings("unchecked")
    final
    // This is safe because T is an array type and newArray is an array of
    // T's component type
    T result = (T) newArray;
    return result;
}
 
Example 18
Project: openjdk-jdk10   File: MethodExitReturnValuesTest.java   View Source Code Vote up 4 votes
static void doit(MethodExitReturnValuesTarg xx) {
    s_show("==========  Testing static methods ================");
    s_bytef();
    s_charf();
    s_doublef();
    s_floatf();
    s_intf();
    s_longf();
    s_shortf();
    s_booleanf();

    s_stringf();
    s_classf();
    s_classLoaderf();
    s_threadf();
    s_threadGroupf();
    s_intArrayf();
    s_nullObjectf();
    s_objectf();
    s_voidf();

    s_show("==========  Testing instance methods ================");
    xx.i_bytef();
    xx.i_charf();
    xx.i_doublef();
    xx.i_floatf();
    xx.i_intf();
    xx.i_longf();
    xx.i_shortf();
    xx.i_booleanf();
    xx.i_stringf();
    xx.i_intArrayf();
    xx.i_classf();
    xx.i_classLoaderf();
    xx.i_threadf();
    xx.i_threadGroupf();
    xx.i_nullObjectf();
    xx.i_objectf();
    xx.i_voidf();

    // Prove it works for native methods too
    s_show("==========  Testing native methods ================");
    StrictMath.sin(doubleValue);
    Array.getByte(arrByte, 0);
    Array.getChar(arrChar, 0);
    Array.getDouble(arrDouble, 0);
    Array.getFloat(arrFloat, 0);
    Array.getInt(arrInt, 0);
    Array.getLong(arrLong, 0);
    Array.getShort(arrShort, 0);
    Array.getBoolean(arrBoolean, 0);
    Array.get(arrObject, 0);
    stringValue.intern();
}
 
Example 19
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 20
Project: jdk8u-jdk   File: PropertyElementHandler.java   View Source Code Vote up 3 votes
/**
 * Performs the search of the getter for the property
 * with specified {@code name} in specified class
 * and returns value of the property.
 *
 * @param bean   the context bean that contains property
 * @param name   the name of the property
 * @param index  the index of the indexed property
 * @return the value of the property
 * @throws IllegalAccessException    if the property is not accesible
 * @throws IntrospectionException    if the bean introspection is failed
 * @throws InvocationTargetException if the getter cannot be invoked
 * @throws NoSuchMethodException     if the getter is not found
 */
private static Object getPropertyValue(Object bean, String name, Integer index) throws IllegalAccessException, IntrospectionException, InvocationTargetException, NoSuchMethodException {
    Class<?> type = bean.getClass();
    if (index == null) {
        return MethodUtil.invoke(findGetter(type, name), bean, new Object[] {});
    } else if (type.isArray() && (name == null)) {
        return Array.get(bean, index);
    } else {
        return MethodUtil.invoke(findGetter(type, name, int.class), bean, new Object[] {index});
    }
}