Example usage for java.lang.reflect Array newInstance

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

Introduction

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

Prototype

public static Object newInstance(Class<?> componentType, int... dimensions)
        throws IllegalArgumentException, NegativeArraySizeException 

Source Link

Document

Creates a new array with the specified component type and dimensions.

Usage

From source file:org.icescrum.core.security.MethodScrumExpressionHandler.java

@SuppressWarnings("unchecked")
public Object filter(Object filterTarget, Expression filterExpression, EvaluationContext ctx) {
    MethodScrumExpressionRoot rootObject = (MethodScrumExpressionRoot) ctx.getRootObject().getValue();
    List retainList;//from w ww.j a  v  a 2s .c  o  m

    if (logger.isDebugEnabled()) {
        logger.debug("Filtering with expression: " + filterExpression.getExpressionString());
    }

    if (filterTarget instanceof Collection) {
        Collection collection = (Collection) filterTarget;
        retainList = new ArrayList(collection.size());

        if (logger.isDebugEnabled()) {
            logger.debug("Filtering collection with " + collection.size() + " elements");
        }
        for (Object filterObject : (Collection) filterTarget) {
            rootObject.setFilterObject(filterObject);

            if (ExpressionUtils.evaluateAsBoolean(filterExpression, ctx)) {
                retainList.add(filterObject);
            }
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Retaining elements: " + retainList);
        }

        collection.clear();
        collection.addAll(retainList);

        return filterTarget;
    }

    if (filterTarget.getClass().isArray()) {
        Object[] array = (Object[]) filterTarget;
        retainList = new ArrayList(array.length);

        if (logger.isDebugEnabled()) {
            logger.debug("Filtering collection with " + array.length + " elements");
        }

        for (int i = 0; i < array.length; i++) {
            rootObject.setFilterObject(array[i]);

            if (ExpressionUtils.evaluateAsBoolean(filterExpression, ctx)) {
                retainList.add(array[i]);
            }
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Retaining elements: " + retainList);
        }

        Object[] filtered = (Object[]) Array.newInstance(filterTarget.getClass().getComponentType(),
                retainList.size());
        for (int i = 0; i < retainList.size(); i++) {
            filtered[i] = retainList.get(i);
        }

        return filtered;
    }

    throw new IllegalArgumentException(
            "Filter target must be a collection or array type, but was " + filterTarget);
}

From source file:jease.cmf.domain.Node.java

/**
 * Returns all children of given class type.
 *//*  w w w  .  ja v  a  2  s.c o m*/
public <E extends Node> E[] getChildren(final Class<E> clazz) {
    return (E[]) Stream.of(getChildren()).filter(node -> clazz.isAssignableFrom(node.getClass()))
            .toArray(size -> (E[]) Array.newInstance(clazz, size));
}

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

/**
 * ??object//ww  w .  j  a  v a2s .  c  om
 * @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.adf.bean.AbsBean.java

/**
 * IMPORT/*from www . j  a va  2s.c o  m*/
 * */
private void setArrayColumn(String col, JSONArray arr)
        throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException {
    Field f;
    f = getClass().getDeclaredField(col);
    f.setAccessible(true);
    Class<?> arrCls = f.getType();
    Class<?> objCls = getArrayObjectClass(arrCls);
    if (objCls != null) {
        Object array = Array.newInstance(objCls, arr.length());
        for (int i = 0; i < arr.length(); i++) {
            Object oi = arr.opt(i);
            if (oi.getClass() == objCls) {
                Array.set(array, i, arr.opt(i));
            } else {
                Constructor<?> cons;
                try {
                    cons = objCls.getDeclaredConstructor(String.class);
                    cons.setAccessible(true);
                    Object obj = cons.newInstance(oi.toString());
                    Array.set(array, i, obj);
                } catch (NoSuchMethodException e) {
                    LogUtil.err("setArrayColumn NoSuchMethodException, col " + col + " :" + e.getMessage());
                } catch (InstantiationException e) {
                    LogUtil.err("setArrayColumn InstantiationException, col " + col + " :" + e.getMessage());
                } catch (InvocationTargetException e) {
                    LogUtil.err("setArrayColumn InvocationTargetException, col " + col + " :" + e.getMessage());
                }
            }
        }
        f.set(this, array);
    } else {
        throw new IllegalArgumentException("Can not get Array Column Object class");
    }
}

From source file:es.caib.zkib.jxpath.util.ValueUtils.java

/**
 * Grows the collection if necessary to the specified size. Returns
 * the new, expanded collection.//from   w w w  . j  a  v  a 2s .c  o  m
 * @param collection to expand
 * @param size desired size
 * @return collection or array
 */
public static Object expandCollection(Object collection, int size) {
    if (collection == null) {
        return null;
    }
    if (size < getLength(collection)) {
        throw new JXPathException("adjustment of " + collection + " to size " + size + " is not an expansion");
    }
    if (collection.getClass().isArray()) {
        Object bigger = Array.newInstance(collection.getClass().getComponentType(), size);
        System.arraycopy(collection, 0, bigger, 0, Array.getLength(collection));
        return bigger;
    }
    if (collection instanceof Collection) {
        while (((Collection) collection).size() < size) {
            ((Collection) collection).add(null);
        }
        return collection;
    }
    throw new JXPathException(
            "Cannot turn " + collection.getClass().getName() + " into a collection of size " + size);
}

From source file:com.sparkplatform.api.core.PropertyAsserter.java

/**
 * See {@link #assertBasicGetterSetterBehavior(Object,String)} method. Only difference is that here we accept an
 * explicit argument for the setter method.
 *
 * @param target   the object on which to invoke the getter and setter
 * @param property the property name, e.g. "firstName"
 * @param argument the property value, i.e. the value the setter will be invoked with
 *///ww  w. j  av  a2s .  co  m
public static void assertBasicGetterSetterBehavior(Object target, String property, Object argument) {
    try {
        PropertyDescriptor descriptor = new PropertyDescriptor(property, target.getClass());
        Object arg = argument;
        Class type = descriptor.getPropertyType();
        if (arg == null) {
            if (type.isArray()) {
                arg = Array.newInstance(type.getComponentType(), new int[] { TEST_ARRAY_SIZE });
            } else if (type.isEnum()) {
                arg = type.getEnumConstants()[0];
            } else if (TYPE_ARGUMENTS.containsKey(type)) {
                arg = TYPE_ARGUMENTS.get(type);
            } else {
                arg = invokeDefaultConstructorEvenIfPrivate(type);
            }
        }

        Method writeMethod = descriptor.getWriteMethod();
        Method readMethod = descriptor.getReadMethod();

        writeMethod.invoke(target, arg);
        Object propertyValue = readMethod.invoke(target);
        if (type.isPrimitive()) {
            assertEquals(property + " getter/setter failed test", arg, propertyValue);
        } else {
            assertSame(property + " getter/setter failed test", arg, propertyValue);
        }
    } catch (IntrospectionException e) {
        String msg = "Error creating PropertyDescriptor for property [" + property
                + "]. Do you have a getter and a setter?";
        log.error(msg, e);
        fail(msg);
    } catch (IllegalAccessException e) {
        String msg = "Error accessing property. Are the getter and setter both accessible?";
        log.error(msg, e);
        fail(msg);
    } catch (InvocationTargetException e) {
        String msg = "Error invoking method on target";
        log.error(msg, e);
        fail(msg);
    }
}

From source file:net.drgnome.virtualpack.util.Util.java

public static <T> T[] merge(T[]... objects) {
        ArrayList<T> list = new ArrayList<T>();
        for (T[] array : objects) {
            if (array == null) {
                continue;
            }/*from  www.ja  v  a  2 s .com*/
            for (T obj : array) {
                if (obj == null) {
                    continue;
                }
                if (!list.contains(obj)) {
                    list.add(obj);
                }
            }
        }
        return list.toArray((T[]) Array.newInstance(objects[0].getClass().getComponentType(), list.size()));
    }

From source file:de.alpharogroup.lang.object.CloneObjectExtensions.java

/**
 * Try to clone the given object./*from w ww .j ava2s  .  com*/
 *
 * @param object
 *            The object to clone.
 * @return The cloned object or null if the clone process failed.
 * @throws NoSuchMethodException
 *             Thrown if a matching method is not found or if the name is "&lt;init&gt;"or
 *             "&lt;clinit&gt;".
 * @throws SecurityException
 *             Thrown if the security manager indicates a security violation.
 * @throws IllegalAccessException
 *             Thrown if this {@code Method} object is enforcing Java language access control
 *             and the underlying method is inaccessible.
 * @throws IllegalArgumentException
 *             Thrown if an illegal argument is given
 * @throws InvocationTargetException
 *             Thrown if the property accessor method throws an exception
 * @throws ClassNotFoundException
 *             occurs if a given class cannot be located by the specified class loader
 * @throws InstantiationException
 *             Thrown if one of the following reasons: the class object
 *             <ul>
 *             <li>represents an abstract class</li>
 *             <li>represents an interface</li>
 *             <li>represents an array class</li>
 *             <li>represents a primitive type</li>
 *             <li>represents {@code void}</li>
 *             <li>has no nullary constructor</li>
 *             </ul>
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Object cloneObject(final Object object)
        throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, ClassNotFoundException, InstantiationException, IOException {
    Object clone = null;
    // Try to clone the object if it implements Serializable.
    if (object instanceof Serializable) {
        clone = SerializedObjectExtensions.copySerializedObject((Serializable) object);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object if it is Cloneble.
    if (clone == null && object instanceof Cloneable) {

        if (object.getClass().isArray()) {
            final Class<?> componentType = object.getClass().getComponentType();
            if (componentType.isPrimitive()) {
                int length = Array.getLength(object);
                clone = Array.newInstance(componentType, length);
                while (length-- > 0) {
                    Array.set(clone, length, Array.get(object, length));
                }
            } else {
                clone = ((Object[]) object).clone();
            }
            if (clone != null) {
                return clone;
            }
        }
        final Class<?> clazz = object.getClass();
        final Method cloneMethod = clazz.getMethod("clone", (Class[]) null);
        clone = cloneMethod.invoke(object, (Object[]) null);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object by copying all his properties with
    // the BeanUtils.copyProperties() method.
    if (clone == null) {
        clone = ReflectionExtensions.getNewInstance(object);
        BeanUtils.copyProperties(clone, object);
    }
    return clone;
}

From source file:br.msf.commons.util.ArrayUtils.java

/**
 * Returns an empty array (non-null) if the given one was null, else, return the given array itself.
 *
 * @param <T>       Type of array elements.
 * @param itemClass Class of the elements for the resulting array.
 * @param array     The array to be evaluated.
 * @return An empty array (non-null) if the given one was null, or the given array itself otherwise.
 *//* w w  w.  j a v a 2  s.  co m*/
@SuppressWarnings("unchecked")
public static <T extends Object> T[] getNullSafeArray(final Class<T> itemClass, final T[] array) {
    return array != null ? array : (T[]) Array.newInstance(itemClass, getTotalSize(array));
}

From source file:jofc2.OFC.java

/**
 * Convenience method for converting Collections to Arrays. You can use this
 * where the API has limited support for collections:
 * getLabels().addLabels(OFC.toArray(stringList, String.class));
 * /*  ww w. j  a  v  a  2  s .  c  o  m*/
 * @param collection
 *            The collection to use
 * @param type
 *            The supertype for the collection. This will commonly be
 *            Integer, Number, etc.
 * @return the array of the collection
 */
@SuppressWarnings("unchecked")
public static <T> T[] toArray(Collection<T> collection, Class<? extends T> type) {
    return collection.toArray((T[]) Array.newInstance(type, collection.size()));
}