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: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 ww  .j av a2 s  .co m*/
    return sourceWrapper;
}

From source file:ArrayIterator.java

/**
 * Sets the array that the ArrayIterator should iterate over.
 * /*from   w  w  w .j a  v a 2  s.  c  om*/
 * If an array has previously been set (using the single-arg constructor
 * or this method) then that array is discarded in favour of this one.
 * Iteration is restarted at the start of the new array.
 * Although this can be used to reset iteration, the {@link #clear()} method
 * is a more effective choice.
 *
 * @param array the array that the iterator should iterate over.
 * @throws IllegalArgumentException if <code>array</code> is not an array.
 * @throws NullPointerException if <code>array</code> is <code>null</code>
 */
private void setArray(final Object array) {
    // Array.getLength throws IllegalArgumentException if the object is not
    // an array or NullPointerException if the object is null.  This call
    // is made before saving the array and resetting the index so that the
    // array iterator remains in a consistent state if the argument is not
    // an array or is null.
    this.endIndex = Array.getLength(array);
    this.array = array;
    this.index = 0;
}

From source file:edu.ucla.stat.SOCR.chart.SuperXYZChart.java

/**
   * //from w  ww  .ja  va2s.c  om
   * @param isDemo data come from demo(true) or dataTable(false)
   * @return
   */
protected XYZDataset createDataset(boolean isDemo) {
    if (isDemo) {
        XYZDataset dataset = new SampleXYZDataset();
        domainLabel = "X";
        rangeLabel = "Y";
        return dataset;

    } else {
        setXYZArray();
        int len = Array.getLength(x);

        /*   Object[] xData = new Object[len]; 
           Object[] yData = new Object[len]; 
           Object[] zData = new Object[len]; 
                
           for (int i=0; i<len; i++){
              xData[i]=new Double(x[i]);
              yData[i]=new Double(y[i]);
              zData[i]=new Double(z[i]);
           }
           // create the dataset... 
           DefaultContourDataset dataset = new DefaultContourDataset((Comparable)independentHeaders[0].substring(0,independentHeaders[0].indexOf(":")), xData, yData, zData); */

        double[][] data = new double[3][len];
        for (int i = 0; i < len; i++) {
            data[0][i] = x[i];
            data[1][i] = y[i];
            data[2][i] = z[i] * zShrinkPercent / 100;
        }
        DefaultXYZDataset dataset = new DefaultXYZDataset();
        String serieName = independentHeaders[0];
        if (independentHeaders[0].indexOf(":") != -1)
            serieName = independentHeaders[0].substring(0, independentHeaders[0].indexOf(":"));

        dataset.addSeries((Comparable) serieName, data);
        return dataset;
    }

}

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));
    }// ww w. ja  va  2s.  co  m
    return wrapperArray;
}

From source file:com.higgses.griffin.annotation.app.GinInjector.java

@SuppressWarnings("ConstantConditions")
private static void injectObject(Object handler, ViewFinder finder) {

    Class<?> handlerType = handler.getClass();

    // inject view
    Field[] fields = handlerType.getDeclaredFields();
    if (fields != null && fields.length > 0) {
        for (Field field : fields) {
            GinInjectView viewInject = field.getAnnotation(GinInjectView.class);
            if (viewInject != null) {
                try {
                    View view = finder.findViewById(viewInject.id(), viewInject.parentId());
                    if (view != null) {
                        field.setAccessible(true);
                        field.set(handler, view);
                    }//from   w  ww . ja v  a2s  . com
                } catch (Throwable e) {
                    LogUtils.e(e.getMessage(), e);
                }
            } else {
                ResInject resInject = field.getAnnotation(ResInject.class);
                if (resInject != null) {
                    try {
                        Object res = ResLoader.loadRes(resInject.type(), finder.getContext(), resInject.id());
                        if (res != null) {
                            field.setAccessible(true);
                            field.set(handler, res);
                        }
                    } catch (Throwable e) {
                        LogUtils.e(e.getMessage(), e);
                    }
                } else {
                    PreferenceInject preferenceInject = field.getAnnotation(PreferenceInject.class);
                    if (preferenceInject != null) {
                        try {
                            Preference preference = finder.findPreference(preferenceInject.value());
                            if (preference != null) {
                                field.setAccessible(true);
                                field.set(handler, preference);
                            }
                        } catch (Throwable e) {
                            LogUtils.e(e.getMessage(), e);
                        }
                    }
                }
            }
        }
    }

    // inject event
    Method[] methods = handlerType.getDeclaredMethods();
    if (methods != null && methods.length > 0) {
        for (Method method : methods) {
            Annotation[] annotations = method.getDeclaredAnnotations();
            if (annotations != null && annotations.length > 0) {
                for (Annotation annotation : annotations) {
                    Class<?> annType = annotation.annotationType();
                    if (annType.getAnnotation(EventBase.class) != null) {
                        method.setAccessible(true);
                        try {
                            // ProGuard-keep class * extends
                            // java.lang.annotation.Annotation { *; }
                            Method valueMethod = annType.getDeclaredMethod("id");
                            Method parentIdMethod = null;
                            try {
                                parentIdMethod = annType.getDeclaredMethod("parentId");
                            } catch (Throwable e) {
                            }
                            Object values = valueMethod.invoke(annotation);
                            Object parentIds = parentIdMethod == null ? null
                                    : parentIdMethod.invoke(annotation);
                            int parentIdsLen = parentIds == null ? 0 : Array.getLength(parentIds);
                            int len = Array.getLength(values);
                            for (int i = 0; i < len; i++) {
                                ViewInjectInfo info = new ViewInjectInfo();
                                info.value = Array.get(values, i);
                                info.parentId = parentIdsLen > i ? (Integer) Array.get(parentIds, i) : 0;
                                EventListenerManager.addEventMethod(finder, info, annotation, handler, method);
                            }
                        } catch (Throwable e) {
                            LogUtils.e(e.getMessage(), e);
                        }
                    }
                }
            }
        }
    }
}

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

/**
 * {@inheritDoc}/*  w ww .j  av  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);
}

From source file:net.kemuri9.sling.filesystemprovider.impl.PersistenceHelper.java

/**
 * Create a {@link JSONObject} that represents the specified object.
 * @param obj the object to create a JSONObject representation for.
 * @return the JSONObject representation of the object.
 * @throws JSONException if an error occurs on creating the JSON data
 *//*from www  .j  a v  a  2 s .c  o m*/
static JSONObject createJSONPropertyObject(Object obj) throws JSONException {
    String type = Object.class.getName().toString();
    boolean isArray = false;
    if (obj != null) {
        if (obj.getClass().isArray()) {
            isArray = true;
            Class<?> elemType = obj.getClass().getComponentType();
            if (elemType.isArray()) {
                throw new IllegalArgumentException("nested array types are not supported");
            }
            type = elemType.getName();
        } else {
            type = obj.getClass().getName().toString();
        }
    }

    JSONObject jsonObj = new JSONObject();
    jsonObj.put(FSPConstants.JSON_KEY_TYPE, type);
    boolean isBinary = false;
    if (isArray) {
        int arrSize = Array.getLength(obj);
        JSONArray arr = new JSONArray();
        jsonObj.put(FSPConstants.JSON_KEY_VALUES, arr);
        for (int arr_i = 0; arr_i < arrSize; ++arr_i) {
            Object arr_val_i = Array.get(obj, arr_i);
            Object storage = convertToJSONStorage(arr_val_i);
            if (storage instanceof JSONStorage) {
                JSONStorage jsonStore = (JSONStorage) storage;
                isBinary |= jsonStore.isBinary;
                storage = jsonStore.value;
            }
            arr.put(storage);
        }
    } else {
        // singly valued type
        Object storage = convertToJSONStorage(obj);
        if (storage instanceof JSONStorage) {
            JSONStorage jsonStore = (JSONStorage) storage;
            storage = jsonStore.value;
            isBinary = jsonStore.isBinary;
        }
        jsonObj.put(FSPConstants.JSON_KEY_VALUE, storage);
    }
    if (isBinary) {
        jsonObj.put(FSPConstants.JSON_KEY_BINARY, true);
    }

    return jsonObj;
}

From source file:org.apache.cayenne.log.CommonsJdbcEventLogger.java

void sqlLiteralForObject(StringBuilder buffer, Object object) {
    if (object == null) {
        buffer.append("NULL");
    } else if (object instanceof String) {
        buffer.append('\'');
        // lets escape quotes
        String literal = (String) object;
        if (literal.length() > TRIM_VALUES_THRESHOLD) {
            literal = literal.substring(0, TRIM_VALUES_THRESHOLD) + "...";
        }/*  w  w  w.j a va  2  s .c  o m*/

        int curPos = 0;
        int endPos = 0;

        while ((endPos = literal.indexOf('\'', curPos)) >= 0) {
            buffer.append(literal.substring(curPos, endPos + 1)).append('\'');
            curPos = endPos + 1;
        }

        if (curPos < literal.length())
            buffer.append(literal.substring(curPos));

        buffer.append('\'');
    }
    // handle byte pretty formatting
    else if (object instanceof Byte) {
        IDUtil.appendFormattedByte(buffer, ((Byte) object).byteValue());
    } else if (object instanceof Number) {
        // process numeric value (do something smart in the future)
        buffer.append(object);
    } else if (object instanceof java.sql.Date) {
        buffer.append('\'').append(object).append('\'');
    } else if (object instanceof java.sql.Time) {
        buffer.append('\'').append(object).append('\'');
    } else if (object instanceof java.util.Date) {
        long time = ((java.util.Date) object).getTime();
        buffer.append('\'').append(new java.sql.Timestamp(time)).append('\'');
    } else if (object instanceof java.util.Calendar) {
        long time = ((java.util.Calendar) object).getTimeInMillis();
        buffer.append(object.getClass().getName()).append('(').append(new java.sql.Timestamp(time)).append(')');
    } else if (object instanceof Character) {
        buffer.append(((Character) object).charValue());
    } else if (object instanceof Boolean) {
        buffer.append('\'').append(object).append('\'');
    } else if (object instanceof Enum<?>) {
        // buffer.append(object.getClass().getName()).append(".");
        buffer.append(((Enum<?>) object).name()).append("=");
        if (object instanceof ExtendedEnumeration) {
            Object value = ((ExtendedEnumeration) object).getDatabaseValue();
            if (value instanceof String)
                buffer.append("'");
            buffer.append(value);
            if (value instanceof String)
                buffer.append("'");
        } else {
            buffer.append(((Enum<?>) object).ordinal());
            // FIXME -- this isn't quite right
        }
    } else if (object instanceof SQLParameterBinding) {
        sqlLiteralForObject(buffer, ((SQLParameterBinding) object).getValue());
    } else if (object.getClass().isArray()) {
        buffer.append("< ");

        int len = Array.getLength(object);
        boolean trimming = false;
        if (len > TRIM_VALUES_THRESHOLD) {
            len = TRIM_VALUES_THRESHOLD;
            trimming = true;
        }

        for (int i = 0; i < len; i++) {
            if (i > 0) {
                buffer.append(",");
            }
            sqlLiteralForObject(buffer, Array.get(object, i));
        }

        if (trimming) {
            buffer.append("...");
        }

        buffer.append('>');
    } else {
        buffer.append(object.getClass().getName()).append("@").append(System.identityHashCode(object));
    }
}

From source file:net.solarnetwork.web.support.JSONView.java

private Collection<?> getPrimitiveCollection(Object array) {
    int len = Array.getLength(array);
    List<Object> result = new ArrayList<Object>(len);
    for (int i = 0; i < len; i++) {
        result.add(Array.get(array, i));
    }/*from w  ww .  j a va  2  s. c  o  m*/
    return result;
}

From source file:edu.psu.chemxseer.structure.util.ArrayIterator.java

/**
 * Sets the array that the ArrayIterator should iterate over.
 * //from  w ww.  ja  v a2s .c  om
 * If an array has previously been set (using the single-arg constructor or
 * this method) then that array is discarded in favour of this one.
 * Iteration is restarted at the start of the new array. Although this can
 * be used to reset iteration, the {@link #clear()} method is a more
 * effective choice.
 * 
 * @param array
 *            the array that the iterator should iterate over.
 * @throws IllegalArgumentException
 *             if <code>array</code> is not an array.
 * @throws NullPointerException
 *             if <code>array</code> is <code>null</code>
 */
private void setArray(final Object array) {
    // Array.getLength throws IllegalArgumentException if the object is not
    // an array or NullPointerException if the object is null. This call
    // is made before saving the array and resetting the index so that the
    // array iterator remains in a consistent state if the argument is not
    // an array or is null.
    this.endIndex = Array.getLength(array);
    this.array = array;
    this.index = 0;
}