Example usage for java.lang.reflect Array getLength

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

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public static native int getLength(Object array) throws IllegalArgumentException;

Source Link

Document

Returns the length of the specified array object, as an int .

Usage

From source file:solidstack.reflect.Dumper.java

public void dumpTo(Object o, DumpWriter out) {
    try {/*from   w w  w .jav a 2  s  .  co m*/
        if (o == null) {
            out.append("<null>");
            return;
        }
        Class<?> cls = o.getClass();
        if (cls == String.class) {
            out.append("\"").append(((String) o).replace("\\", "\\\\").replace("\n", "\\n").replace("\r", "\\r")
                    .replace("\t", "\\t").replace("\"", "\\\"")).append("\"");
            return;
        }
        if (o instanceof CharSequence) {
            out.append("(").append(o.getClass().getName()).append(")");
            dumpTo(o.toString(), out);
            return;
        }
        if (cls == char[].class) {
            out.append("(char[])");
            dumpTo(String.valueOf((char[]) o), out);
            return;
        }
        if (cls == byte[].class) {
            out.append("byte[").append(Integer.toString(((byte[]) o).length)).append("]");
            return;
        }
        if (cls == Class.class) {
            out.append(((Class<?>) o).getCanonicalName()).append(".class");
            return;
        }
        if (cls == File.class) {
            out.append("File( \"").append(((File) o).getPath()).append("\" )");
            return;
        }
        if (cls == AtomicInteger.class) {
            out.append("AtomicInteger( ").append(Integer.toString(((AtomicInteger) o).get())).append(" )");
            return;
        }
        if (cls == AtomicLong.class) {
            out.append("AtomicLong( ").append(Long.toString(((AtomicLong) o).get())).append(" )");
            return;
        }
        if (o instanceof ClassLoader) {
            out.append(o.getClass().getCanonicalName());
            return;
        }

        if (cls == java.lang.Short.class || cls == java.lang.Long.class || cls == java.lang.Integer.class
                || cls == java.lang.Float.class || cls == java.lang.Byte.class
                || cls == java.lang.Character.class || cls == java.lang.Double.class
                || cls == java.lang.Boolean.class || cls == BigInteger.class || cls == BigDecimal.class) {
            out.append("(").append(cls.getSimpleName()).append(")").append(o.toString());
            return;
        }

        String className = cls.getCanonicalName();
        if (className == null)
            className = cls.getName();
        out.append(className);

        if (this.skip.contains(className) || o instanceof java.lang.Thread) {
            out.append(" (skipped)");
            return;
        }

        Integer id = this.visited.get(o);
        if (id == null) {
            id = ++this.id;
            this.visited.put(o, id);
            if (!this.hideIds)
                out.append(" <id=" + id + ">");
        } else {
            out.append(" <refid=" + id + ">");
            return;
        }

        if (cls.isArray()) {
            if (Array.getLength(o) == 0)
                out.append(" []");
            else {
                out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst();
                int rowCount = Array.getLength(o);
                for (int i = 0; i < rowCount; i++) {
                    out.comma();
                    dumpTo(Array.get(o, i), out);
                }
                out.newlineOrSpace().unIndent().append("]");
            }
        } else if (o instanceof Collection && !this.overriddenCollection.contains(className)) {
            Collection<?> list = (Collection<?>) o;
            if (list.isEmpty())
                out.append(" []");
            else {
                out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst();
                for (Object value : list) {
                    out.comma();
                    dumpTo(value, out);
                }
                out.newlineOrSpace().unIndent().append("]");
            }
        } else if (o instanceof Properties && !this.overriddenCollection.contains(className)) // Properties is a Map, so it must come before the Map
        {
            Field def = cls.getDeclaredField("defaults");
            if (!def.isAccessible())
                def.setAccessible(true);
            Properties defaults = (Properties) def.get(o);
            Hashtable<?, ?> map = (Hashtable<?, ?>) o;
            out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst();
            for (Map.Entry<?, ?> entry : map.entrySet()) {
                out.comma();
                dumpTo(entry.getKey(), out);
                out.append(": ");
                dumpTo(entry.getValue(), out);
            }
            if (defaults != null && !defaults.isEmpty()) {
                out.comma().append("defaults: ");
                dumpTo(defaults, out);
            }
            out.newlineOrSpace().unIndent().append("]");
        } else if (o instanceof Map && !this.overriddenCollection.contains(className)) {
            Map<?, ?> map = (Map<?, ?>) o;
            if (map.isEmpty())
                out.append(" []");
            else {
                out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst();
                for (Map.Entry<?, ?> entry : map.entrySet()) {
                    out.comma();
                    dumpTo(entry.getKey(), out);
                    out.append(": ");
                    dumpTo(entry.getValue(), out);
                }
                out.newlineOrSpace().unIndent().append("]");
            }
        } else if (o instanceof Method) {
            out.newlineOrSpace().append("{").newlineOrSpace().indent().setFirst();

            Field field = cls.getDeclaredField("clazz");
            if (!field.isAccessible())
                field.setAccessible(true);
            out.comma().append("clazz").append(": ");
            dumpTo(field.get(o), out);

            field = cls.getDeclaredField("name");
            if (!field.isAccessible())
                field.setAccessible(true);
            out.comma().append("name").append(": ");
            dumpTo(field.get(o), out);

            field = cls.getDeclaredField("parameterTypes");
            if (!field.isAccessible())
                field.setAccessible(true);
            out.comma().append("parameterTypes").append(": ");
            dumpTo(field.get(o), out);

            field = cls.getDeclaredField("returnType");
            if (!field.isAccessible())
                field.setAccessible(true);
            out.comma().append("returnType").append(": ");
            dumpTo(field.get(o), out);

            out.newlineOrSpace().unIndent().append("}");
        } else {
            ArrayList<Field> fields = new ArrayList<Field>();
            while (cls != Object.class) {
                Field[] fs = cls.getDeclaredFields();
                for (Field field : fs)
                    fields.add(field);
                cls = cls.getSuperclass();
            }

            Collections.sort(fields, new Comparator<Field>() {
                public int compare(Field left, Field right) {
                    return left.getName().compareTo(right.getName());
                }
            });

            if (fields.isEmpty())
                out.append(" {}");
            else {
                out.newlineOrSpace().append("{").newlineOrSpace().indent().setFirst();
                for (Field field : fields)
                    if ((field.getModifiers() & Modifier.STATIC) == 0)
                        if (!this.hideTransients || (field.getModifiers() & Modifier.TRANSIENT) == 0) {
                            out.comma().append(field.getName()).append(": ");

                            if (!field.isAccessible())
                                field.setAccessible(true);

                            if (field.getType().isPrimitive())
                                if (field.getType() == boolean.class) // TODO More?
                                    out.append(field.get(o).toString());
                                else
                                    out.append("(").append(field.getType().getName()).append(")")
                                            .append(field.get(o).toString());
                            else
                                dumpTo(field.get(o), out);
                        }
                out.newlineOrSpace().unIndent().append("}");
            }
        }
    } catch (IOException e) {
        throw new FatalIOException(e);
    } catch (Exception e) {
        dumpTo(e.toString(), out);
    }
}

From source file:com.manydesigns.elements.forms.TableForm.java

public void writeToObject(Object obj) {
    Class clazz = obj.getClass();
    if (clazz.isArray()) { // Tratta obj come un array
        // Scorre tutti gli elementi dell'array obj,
        // indipendentemente da quante righe ci sono nel table form.
        // Eventualmente lancia Eccezione.
        final int arrayLength = Array.getLength(obj);
        for (int i = 0; i < arrayLength; i++) {
            Object currentObj = Array.get(obj, i);
            rows[i].writeToObject(currentObj);
        }/*  www  . j  a  va 2 s  .  com*/
    } else if (Collection.class.isAssignableFrom(clazz)) {
        // Tratta obj come collection
        Collection collection = (Collection) obj;

        int i = 0;
        for (Object currentObj : collection) {
            rows[i].writeToObject(currentObj);
            i++;
        }
    }
}

From source file:ArraysX.java

/**
 * Concat the two specified array./*  w ww  .j  a v  a2s .  c  om*/
 *
 * <p>The array could be an array of objects or primiitives.
 *
 * @param ary the array
 * @param ary1 the array
 * @return an array concat the ary and ary1
 * @exception IllegalArgumentException if ary and ary1 component type are different
 */
public static final Object concat(Object ary, Object ary1) {
    int len = Array.getLength(ary) + Array.getLength(ary1);

    if (!ary.getClass().getComponentType().equals(ary1.getClass().getComponentType()))
        throw new IllegalArgumentException("These concated array component type are different.");
    Object dst = Array.newInstance(ary.getClass().getComponentType(), len);

    System.arraycopy(ary, 0, dst, 0, Array.getLength(ary));
    System.arraycopy(ary1, 0, dst, Array.getLength(ary), Array.getLength(ary1));

    return dst;
}

From source file:org.apache.openjpa.util.ProxyManagerImpl.java

public Object copyArray(Object orig) {
    if (orig == null)
        return null;

    try {//from  w w w . j  a v a2s. co m
        int length = Array.getLength(orig);
        Object array = Array.newInstance(orig.getClass().getComponentType(), length);

        System.arraycopy(orig, 0, array, 0, length);
        return array;
    } catch (Exception e) {
        throw new UnsupportedException(_loc.get("bad-array", e.getMessage()), e);
    }
}

From source file:com.chadekin.jadys.commons.expression.impl.SqlExpressionFactory.java

private static boolean isBlankValue(Object value) {
    boolean isBlank = value == null || StringUtils.isBlank(value.toString());
    if (!isBlank) {
        boolean isEmptyCollection = value instanceof Collection && CollectionUtils.isEmpty((Collection) value);
        boolean isEmptyArray = value.getClass().isArray() && Array.getLength(value) == 0;
        isBlank = isEmptyCollection || isEmptyArray;
    }/*from   w  ww  .ja v a2  s  . c  o  m*/
    return isBlank;
}

From source file:org.apache.hawq.pxf.plugins.hdfs.WritableResolver.java

/**
 * Sets customWritable fields and creates a OneRow object.
 *//* ww w.  j  a  va2  s.c  o m*/
@Override
public OneRow setFields(List<OneField> record) throws Exception {
    Writable key = null;

    int colIdx = 0;
    for (Field field : fields) {
        /*
         * extract recordkey based on the column descriptor type
         * and add to OneRow.key
         */
        if (colIdx == recordkeyIndex) {
            key = recordkeyAdapter.convertKeyValue(record.get(colIdx).val);
            colIdx++;
        }

        if (Modifier.isPrivate(field.getModifiers())) {
            continue;
        }

        String javaType = field.getType().getName();
        convertJavaToGPDBType(javaType);
        if (isArray(javaType)) {
            Object value = field.get(userObject);
            int length = Array.getLength(value);
            for (int j = 0; j < length; j++, colIdx++) {
                Array.set(value, j, record.get(colIdx).val);
            }
        } else {
            field.set(userObject, record.get(colIdx).val);
            colIdx++;
        }
    }

    return new OneRow(key, userObject);
}

From source file:com.liferay.portal.template.soy.internal.SoyTemplate.java

protected Object getSoyMapValue(Object value) {
    if (value == null) {
        return null;
    }//from ww w.  j a  v a2s. c  o m

    Class<?> clazz = value.getClass();

    if (ClassUtils.isPrimitiveOrWrapper(clazz) || value instanceof String) {
        return value;
    }

    if (clazz.isArray()) {
        List<Object> newList = new ArrayList<>();

        for (int i = 0; i < Array.getLength(value); i++) {
            Object object = Array.get(value, i);

            newList.add(getSoyMapValue(object));
        }

        return newList;
    }

    if (value instanceof Iterable) {
        @SuppressWarnings("unchecked")
        Iterable<Object> iterable = (Iterable<Object>) value;

        List<Object> newList = new ArrayList<>();

        for (Object object : iterable) {
            newList.add(getSoyMapValue(object));
        }

        return newList;
    }

    if (value instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) value;

        List<Object> newList = new ArrayList<>();

        for (int i = 0; i < jsonArray.length(); i++) {
            Object object = jsonArray.opt(i);

            newList.add(getSoyMapValue(object));
        }

        return newList;
    }

    if (value instanceof Map) {
        Map<Object, Object> map = (Map<Object, Object>) value;

        Map<Object, Object> newMap = new TreeMap<>();

        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            Object newKey = getSoyMapValue(entry.getKey());

            if (newKey == null) {
                continue;
            }

            Object newValue = getSoyMapValue(entry.getValue());

            newMap.put(newKey, newValue);
        }

        return newMap;
    }

    if (value instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) value;

        Map<String, Object> newMap = new TreeMap<>();

        Iterator<String> iterator = jsonObject.keys();

        while (iterator.hasNext()) {
            String key = iterator.next();

            Object object = jsonObject.get(key);

            Object newValue = getSoyMapValue(object);

            newMap.put(key, newValue);
        }

        return newMap;
    }

    if (value instanceof org.json.JSONObject) {
        org.json.JSONObject jsonObject = (org.json.JSONObject) value;

        Map<Object, Object> newMap = new TreeMap<>();

        Iterator<String> iterator = jsonObject.keys();

        while (iterator.hasNext()) {
            String key = iterator.next();

            Object object = jsonObject.opt(key);

            Object newValue = getSoyMapValue(object);

            newMap.put(key, newValue);
        }

        return newMap;
    }

    if (value instanceof SoyRawData) {
        SoyRawData soyRawData = (SoyRawData) value;

        return soyRawData.getValue();
    }

    Map<String, Object> newMap = new TreeMap<>();

    BeanPropertiesUtil.copyProperties(value, newMap);

    if (newMap.isEmpty()) {
        return null;
    }

    return getSoyMapValue(newMap);
}

From source file:com.astamuse.asta4d.web.form.flow.base.BasicFormFlowSnippetTrait.java

/**
 * /*  w w  w.j  a v a2 s.co m*/
 * PriorRenderMethod the value of all the given form's fields.The rendering of cascade forms will be done here as well(recursively call
 * the {@link #renderForm(String, Object, int)}).
 * 
 * @param renderTargetStep
 * @param form
 * @param indexes
 * @return
 * @throws Exception
 */
default Renderer renderValueOfFields(String renderTargetStep, Object form, int[] indexes) throws Exception {
    Renderer render = Renderer.create();
    List<AnnotatedPropertyInfo> fieldList = BasicFormFlowTraitHelper.retrieveRenderTargetFieldList(form);

    for (AnnotatedPropertyInfo field : fieldList) {

        Object v = field.retrieveValue(form);

        CascadeFormField cff = field.getAnnotation(CascadeFormField.class);
        if (cff != null) {
            String containerSelector = cff.containerSelector();

            if (field.getType().isArray()) {// a cascade form for array
                int len = Array.getLength(v);
                List<Renderer> subRendererList = new ArrayList<>(len);
                int loopStart = 0;
                if (renderForEdit(renderTargetStep, form, cff.name())) {
                    // for rendering a template DOM
                    loopStart = -1;
                }
                Class<?> subFormType = field.getType().getComponentType();
                Object subForm;
                for (int i = loopStart; i < len; i++) {
                    int[] newIndex = indexes.clone();

                    // retrieve the form instance
                    if (i >= 0) {
                        newIndex = ArrayUtils.add(newIndex, i);
                        subForm = Array.get(v, i);
                    } else {
                        // create a template instance
                        subForm = createFormInstanceForCascadeFormArrayTemplate(subFormType);
                    }

                    Renderer subRenderer = Renderer.create();

                    // only rewrite the refs for normal instances
                    if (i >= 0) {
                        subRenderer.add(rewriteCascadeFormFieldArrayRef(renderTargetStep, subForm, newIndex));
                    }

                    subRenderer.add(renderForm(renderTargetStep, subForm, newIndex));

                    // hide the template DOM
                    if (i < 0) {
                        subRenderer.add(":root", hideCascadeFormTemplateDOM(subFormType));
                    }

                    subRendererList.add(subRenderer);
                }
                containerSelector = rewriteArrayIndexPlaceHolder(containerSelector, indexes);
                render.add(containerSelector, subRendererList);
            } else {// a simple cascade form

                if (StringUtils.isNotEmpty(containerSelector)) {
                    render.add(containerSelector, renderForm(renderTargetStep, v, indexes));
                } else {
                    render.add(renderForm(renderTargetStep, v, indexes));
                }
            }
            continue;
        }

        if (v == null) {
            @SuppressWarnings("rawtypes")
            ContextDataHolder valueHolder;

            if (field.getField() != null) {
                valueHolder = InjectTrace.getInstanceInjectionTraceInfo(form, field.getField());
            } else {
                valueHolder = InjectTrace.getInstanceInjectionTraceInfo(form, field.getSetter());
            }

            if (valueHolder != null) {
                v = convertRawInjectionTraceDataToRenderingData(field.getName(), field.getType(),
                        valueHolder.getFoundOriginalData());
            }
        }

        BasicFormFlowTraitHelper.FieldRenderingInfo renderingInfo = BasicFormFlowTraitHelper
                .getRenderingInfo(this, field, indexes);

        // render.addDebugger("whole form before: " + field.getName());

        if (renderForEdit(renderTargetStep, form, field.getName())) {
            render.add(renderingInfo.valueRenderer.renderForEdit(renderingInfo.editSelector, v));
        } else {
            render.add(renderingInfo.valueRenderer.renderForDisplay(renderingInfo.editSelector,
                    renderingInfo.displaySelector, v));
        }
    }
    return render;
}

From source file:org.apache.hadoop.hive.metastore.VerifyingObjectStore.java

private static void dumpObject(StringBuilder errorStr, String name, Object p, Class<?> c, int level)
        throws IllegalAccessException {
    String offsetStr = repeat("  ", level);
    if (p == null || c == String.class || c.isPrimitive() || ClassUtils.wrapperToPrimitive(c) != null) {
        errorStr.append(offsetStr).append(name + ": [" + p + "]\n");
    } else if (ClassUtils.isAssignable(c, Iterable.class)) {
        errorStr.append(offsetStr).append(name + " is an iterable\n");
        Iterator<?> i1 = ((Iterable<?>) p).iterator();
        int i = 0;
        while (i1.hasNext()) {
            Object o1 = i1.next();
            Class<?> t = o1 == null ? Object.class : o1.getClass(); // ...
            dumpObject(errorStr, name + "[" + (i++) + "]", o1, t, level + 1);
        }/*from ww w.  ja va2s .c o  m*/
    } else if (c.isArray()) {
        int len = Array.getLength(p);
        Class<?> t = c.getComponentType();
        errorStr.append(offsetStr).append(name + " is an array\n");
        for (int i = 0; i < len; ++i) {
            dumpObject(errorStr, name + "[" + i + "]", Array.get(p, i), t, level + 1);
        }
    } else if (ClassUtils.isAssignable(c, Map.class)) {
        Map<?, ?> c1 = (Map<?, ?>) p;
        errorStr.append(offsetStr).append(name + " is a map\n");
        dumpObject(errorStr, name + ".keys", c1.keySet(), Set.class, level + 1);
        dumpObject(errorStr, name + ".vals", c1.values(), Collection.class, level + 1);
    } else {
        errorStr.append(offsetStr).append(name + " is of type " + c.getCanonicalName() + "\n");
        // TODO: this doesn't include superclass.
        Field[] fields = c.getDeclaredFields();
        AccessibleObject.setAccessible(fields, true);
        for (int i = 0; i < fields.length; i++) {
            Field f = fields[i];
            if (f.getName().indexOf('$') != -1 || Modifier.isStatic(f.getModifiers()))
                continue;
            dumpObject(errorStr, name + "." + f.getName(), f.get(p), f.getType(), level + 1);
        }
    }
}

From source file:com.github.mybatis.spring.MapperFactoryBean.java

private void evalArray(Object arr, StringBuilder sbd) {
    int sz = Array.getLength(arr);
    if (sz == 0) {
        sbd.append("[]");
        return;/*from   ww  w.  j a  v a 2 s  .  c o  m*/
    }
    Class<?> clz = Array.get(arr, 0).getClass();
    if (clz == Byte.class) {
        sbd.append("Byte[").append(sz).append(']');
        return;
    }
    if (isPrimitive(clz)) {
        sbd.append('[');
        int len = Math.min(sz, 10);
        for (int i = 0; i < len; i++) {
            Object obj = Array.get(arr, i);
            if (isPrimitive(obj.getClass())) {
                sbd.append(evalPrimitive(obj));
            } else {
                sbd.append(obj.getClass().getSimpleName()).append(":OBJ");
            }
            sbd.append(',');
        }
        if (sz > 10) {
            sbd.append(",...,len=").append(sz);
        }
        if (sbd.charAt(sbd.length() - 1) == ',') {
            sbd.setCharAt(sbd.length() - 1, ']');
        } else {
            sbd.append(']');
        }
    } else {
        sbd.append("[len=").append(sz).append(']');
    }
}