Example usage for java.lang.reflect Array get

List of usage examples for java.lang.reflect Array get

Introduction

In this page you can find the example usage for java.lang.reflect Array get.

Prototype

public static native Object get(Object array, int index)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

Source Link

Document

Returns the value of the indexed component in the specified array object.

Usage

From source file:io.s4.comm.util.JSONUtil.java

public static Map<String, Object> getMap(Object obj) {
    Map<String, Object> map = new HashMap<String, Object>();
    if (obj != null) {
        if (Map.class.isAssignableFrom(obj.getClass())) {
            return (Map) obj;
        } else {/*from w  ww .j a  v a  2 s  . c  o m*/

            Field[] fields = obj.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                if (!fields[i].isAccessible()) {
                    fields[i].setAccessible(true);
                }
                try {
                    String name = fields[i].getName();
                    Object val = fields[i].get(obj);
                    if (!Modifier.isStatic(fields[i].getModifiers())
                            && !Modifier.isTransient(fields[i].getModifiers())) {
                        if (fields[i].getType().isPrimitive() || knownTypes.contains(fields[i].getType())) {
                            map.put(name, val);
                        } else if (fields[i].getType().isArray()) {
                            int length = Array.getLength(val);
                            Object vals[] = new Object[length];
                            for (int j = 0; j < length; j++) {
                                Object arrVal = Array.get(val, j);
                                if (arrVal.getClass().isPrimitive() || knownTypes.contains(arrVal.getClass())) {
                                    vals[j] = arrVal;
                                } else {
                                    vals[j] = getMap(arrVal);
                                }
                            }
                            map.put(name, vals);
                        } else {
                            map.put(name, getMap(val));
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException("Exception while getting value of " + fields[i], e);
                }
            }
        }
    }
    return map;
}

From source file:com.discovery.darchrow.lang.ArrayUtil.java

/**
 * ?? {@link java.util.Iterator}./*from   www . jav  a2s  .co m*/
 * <p>
 * ??,???with no copying<br>
 * ?, ClassCastException  ,Rats -- ,arrayList ?arrayList.iterator()
 * </p>
 * <p>
 * <b>:</b>{@link Arrays#asList(Object...)} list {@link Array}  ArrayList,
 * {@link java.util.AbstractList#add(int, Object)} ,<br>
 * listadd?, {@link java.lang.UnsupportedOperationException}
 * </p>
 * 
 * @param <T>
 *            the generic type
 * @param arrays
 *            ,? , 
 * @return if (null == arrays) return null;<br>
 *         ?arrays?Object[], {@link Arrays#asList(Object...)}?list,? {@link List#iterator()
 *         t}<br>
 *         ,? Object[],?, {@link Array#getLength(Object)}?, {@link Array#get(Object, int)} list
 * @see Arrays#asList(Object...)
 * @see Array#getLength(Object)
 * @see Array#get(Object, int)
 * @see List#iterator()
 */
@SuppressWarnings({ "unchecked" })
public static <T> Iterator<T> toIterator(Object arrays) {
    if (null == arrays) {
        return null;
    }
    List<T> list = null;
    try {
        // ??,???with no copying
        Object[] objArrays = (Object[]) arrays;
        list = (List<T>) toList(objArrays);
    } catch (ClassCastException e) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("arrays can not cast to Object[],maybe primitive type,values is:{},{}", arrays,
                    e.getMessage());
        }
        // Rats -- 
        int length = Array.getLength(arrays);
        list = new ArrayList<T>(length);
        for (int i = 0; i < length; ++i) {
            Object object = Array.get(arrays, i);
            list.add((T) object);
        }
    }
    return list.iterator();
}

From source file:org.cloudata.core.common.io.CObjectWritable.java

/** Write a {@link CWritable}, {@link String}, primitive type, or an array of
 * the preceding. *//*from  w  w w . j  a  v a  2  s.  com*/
public static void writeObject(DataOutput out, Object instance, Class declaredClass, CloudataConf conf,
        boolean arrayComponent) throws IOException {

    if (instance == null) { // null
        instance = new NullInstance(declaredClass, conf);
        declaredClass = CWritable.class;
        arrayComponent = false;
    }

    if (!arrayComponent) {
        CUTF8.writeString(out, declaredClass.getName()); // always write declared
        //System.out.println("Write:declaredClass.getName():" + declaredClass.getName());
    }

    if (declaredClass.isArray()) { // array
        int length = Array.getLength(instance);
        out.writeInt(length);
        //System.out.println("Write:length:" + length);

        if (declaredClass.getComponentType() == Byte.TYPE) {
            out.write((byte[]) instance);
        } else if (declaredClass.getComponentType() == ColumnValue.class) {
            //ColumnValue?  Deserialize? ?? ?   ?? ?  .
            writeColumnValue(out, instance, declaredClass, conf, length);
        } else {
            for (int i = 0; i < length; i++) {
                writeObject(out, Array.get(instance, i), declaredClass.getComponentType(), conf,
                        !declaredClass.getComponentType().isArray());
            }
        }
    } else if (declaredClass == String.class) { // String
        CUTF8.writeString(out, (String) instance);

    } else if (declaredClass.isPrimitive()) { // primitive type

        if (declaredClass == Boolean.TYPE) { // boolean
            out.writeBoolean(((Boolean) instance).booleanValue());
        } else if (declaredClass == Character.TYPE) { // char
            out.writeChar(((Character) instance).charValue());
        } else if (declaredClass == Byte.TYPE) { // byte
            out.writeByte(((Byte) instance).byteValue());
        } else if (declaredClass == Short.TYPE) { // short
            out.writeShort(((Short) instance).shortValue());
        } else if (declaredClass == Integer.TYPE) { // int
            out.writeInt(((Integer) instance).intValue());
        } else if (declaredClass == Long.TYPE) { // long
            out.writeLong(((Long) instance).longValue());
        } else if (declaredClass == Float.TYPE) { // float
            out.writeFloat(((Float) instance).floatValue());
        } else if (declaredClass == Double.TYPE) { // double
            out.writeDouble(((Double) instance).doubleValue());
        } else if (declaredClass == Void.TYPE) { // void
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declaredClass);
        }
    } else if (declaredClass.isEnum()) { // enum
        CUTF8.writeString(out, ((Enum) instance).name());
    } else if (CWritable.class.isAssignableFrom(declaredClass)) { // Writable
        if (instance.getClass() == declaredClass) {
            out.writeShort(TYPE_SAME); // ? ?? ? ?? 
            //System.out.println("Write:TYPE_SAME:" + TYPE_SAME);

        } else {
            out.writeShort(TYPE_DIFF);
            //System.out.println("Write:TYPE_DIFF:" + TYPE_DIFF);
            CUTF8.writeString(out, instance.getClass().getName());
            //System.out.println("Write:instance.getClass().getName():" + instance.getClass().getName());
        }
        ((CWritable) instance).write(out);
        //System.out.println("Write:instance value");

    } else {
        throw new IOException("Can't write: " + instance + " as " + declaredClass);
    }
}

From source file:com.example.app.profile.ui.user.MembershipOperationsEditorUI.java

@Override
public void init() {
    super.init();

    MessageContainer messages = new MessageContainer(35_000L);

    final SearchSupplierImpl searchSupplier = getSearchSupplier();
    SearchUIImpl.Options options = new SearchUIImpl.Options("Membership Operation Selector");
    options.setSearchOnPageLoad(true);//  w w w .j  a v a2 s. c  om

    options.setSearchActions(Collections.emptyList());
    options.addSearchSupplier(searchSupplier);
    options.setHistory(_history);
    options.setRowExtractor(input -> {
        if (input.getClass().isArray())
            return Array.get(input, 0);
        else
            return input;
    });

    _searchUI = new SearchUIImpl(options);

    Label heading = new Label(createText(MEMBERSHIP_UI_HEADING_FORMAT(), _membership.getProfile().getName(),
            _membership.getMembershipType().getName()));
    heading.setHTMLElement(HTMLElement.h3);

    add(of("search-wrapper membership-operation-search", heading, messages, _searchUI));
}

From source file:com.laidians.utils.ObjectUtils.java

/**
 * ??object/*from  ww  w. j  a v  a 2 s  .  co  m*/
 * @param source
 * @return
 */
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:com.github.erchu.beancp.MapperImpl.java

private <S> Object[] getArrayOfPrimitiveTypeWrapper(Class sourceClass, final S source)
        throws IllegalArgumentException, NegativeArraySizeException, ArrayIndexOutOfBoundsException {
    Class<?> arrayElementWrapperClass = ClassUtils.primitiveToWrapper(sourceClass.getComponentType());
    int arrayLength = Array.getLength(source);
    Object[] sourceWrapper = (Object[]) Array.newInstance(arrayElementWrapperClass, arrayLength);
    for (int i = 0; i < arrayLength; i++) {
        sourceWrapper[i] = Array.get(source, i);
    }/*from  w  w  w  . jav  a 2 s  .  c  o m*/
    return sourceWrapper;
}

From source file:org.eclipse.ecr.core.storage.sql.coremodel.SQLDocumentLive.java

protected static boolean sameArray(Object a, Object b) {
    Class<?> acls = a.getClass();
    Class<?> bcls = b.getClass();
    if (!acls.isArray() || !bcls.isArray() || Array.getLength(a) != Array.getLength(b)) {
        return false;
    }//from  www.  ja v  a2  s  . co m
    for (int i = 0; i < Array.getLength(a); i++) {
        if (!same(Array.get(a, i), Array.get(b, i))) {
            return false;
        }
    }
    return true;
}

From source file:org.apache.sling.models.impl.injectors.ValueMapInjector.java

private Object wrapArray(Object primitiveArray, Class<?> wrapperType) {
    int length = Array.getLength(primitiveArray);
    Object wrapperArray = Array.newInstance(wrapperType, length);
    for (int i = 0; i < length; i++) {
        Array.set(wrapperArray, i, Array.get(primitiveArray, i));
    }/*from w  w  w .jav a2s.c o  m*/
    return wrapperArray;
}

From source file:jp.terasoluna.fw.web.struts.form.ValidatorActionFormEx.java

/**
 * wCfbNXv?peBl?B/*from  w  w  w .j  ava 2s  .  c o m*/
 *
 * @param name ?v?peB
 * @param index ?CfbNX
 * @return v?peBl
 */
public Object getIndexedValue(String name, int index) {
    Object field = null;
    try {
        field = BeanUtil.getBeanProperty(this, name);
    } catch (PropertyAccessException e) {
        // DynaValidatorActionFormExdl??A
        // O????s?B
    }
    if (field == null) {
        throw new NullPointerException("No indexed value for '" + name + "[" + index + "]'");
    } else if (field.getClass().isArray()) {
        try {
            return (Array.get(field, index));
        } catch (ArrayIndexOutOfBoundsException e) {
            return null;
        }
    } else if (field instanceof List) {
        try {
            return ((List) field).get(index);
        } catch (IndexOutOfBoundsException e) {
            return null;
        }
    } else {
        throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]'");
    }
}

From source file:org.nabucco.alfresco.enhScriptEnv.common.script.converter.rhino.NativeArrayConverter.java

/**
 * {@inheritDoc}//from   w  ww .j a v a2  s.c om
 */
@Override
public Object convertValueForScript(final Object value, final ValueConverter globalDelegate,
        final Class<?> expectedClass) {
    final Object[] arr;
    int arrIdx = 0;
    if (value instanceof Collection<?>) {
        final Collection<?> coll = (Collection<?>) value;
        arr = new Object[coll.size()];
        for (final Object element : coll) {
            arr[arrIdx++] = globalDelegate.convertValueForScript(element);
        }
    } else if (value.getClass().isArray()) {
        final int length = Array.getLength(value);
        arr = new Object[length];
        for (int idx = 0; idx < length; idx++) {
            arr[arrIdx++] = globalDelegate.convertValueForScript(Array.get(value, idx));
        }
    } else {
        throw new IllegalArgumentException("value must be either collection or array");
    }

    return new NativeArray(arr);
}