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:illab.nabal.util.Util.java

/**
 * Concat multiple arrays at once.//from w  w w  .j a v  a2  s . co m
 * 
 * @param firstArray
 * @param restArrays
 * @return an array containing values from all given arrays
 */
@SuppressWarnings("unchecked")
public static <T> T[] concatAllArrays(T[] firstArray, T[]... restArrays) {

    // try not to reassign parameters
    T[] leftSideArray = firstArray;

    // defend against null or empty array
    if (leftSideArray == null || leftSideArray.length == 0) {
        leftSideArray = (T[]) new Object[0];
    }

    int totalLength = leftSideArray.length;
    for (T[] array : restArrays) {
        if (array != null && array.length > 0) {
            totalLength += array.length;
        }
    }

    // avoid using Arrays#copyOf for backward compatibility
    //T[] result = Arrays.copyOf(leftSideArray, totalLength);

    // instead of using Arrays#copyOf, use below 3 lines
    Class<?> type = leftSideArray.getClass().getComponentType();
    T[] result = (T[]) Array.newInstance(type, totalLength);
    System.arraycopy(leftSideArray, 0, result, 0, leftSideArray.length);

    int offset = leftSideArray.length;
    for (T[] array : restArrays) {
        if (array != null && array.length > 0) {
            System.arraycopy(array, 0, result, offset, array.length);
            offset += array.length;
        }
    }

    return result;
}

From source file:com.sinosoft.one.data.jade.statement.SelectQuerier.java

public Object execute(SQLType sqlType, StatementRuntime runtime) {
    String sql = runtime.getSQL();
    Object[] args = runtime.getArgs();
    DataAccess dataAccess = new DataAccessImpl(em);
    List<?> listResult = null;
    Pageable pageable = null;/*from w ww. ja  v  a2 s  . c o  m*/
    Sort sort = null;
    boolean isPage = false;
    boolean isSort = false;
    Map<String, Object> paramMap = runtime.getParameters();
    for (String key : paramMap.keySet()) {
        if (paramMap.get(key) instanceof Pageable) {
            pageable = (Pageable) paramMap.get(key);
            isPage = true;
        } else if (paramMap.get(key) instanceof Sort) {
            sort = (Sort) paramMap.get(key);
            isSort = true;
        }
    }
    if (isPage && !isSort) {
        if (returnType == Page.class) {
            String countSql = parseCountSql(sql);
            Page<?> page = dataAccess.selectByPage(pageable, sql, countSql, args, rowMapper);
            return page;
        } else {
            try {
                log.error("The return type[" + returnType + "] must be " + Page.class);
                throw new Exception("The return type [\"+returnType+\"] is invalid");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } else if (!isPage && isSort) {
        return dataAccess.selectBySort(sort, sql, args, rowMapper);
    } else if (isPage && isSort) {
        try {
            log.error("Can not use Params:[" + Pageable.class + " and " + Sort.class + "at the same time.");
            throw new Exception(
                    "Can not use Params:[" + Pageable.class + " and " + Sort.class + "at the same time.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {

        listResult = dataAccess.select(sql, args, rowMapper);
        final int sizeResult = listResult.size();

        //  Result ?
        if (returnType.isAssignableFrom(List.class)) {

            //   List ?
            return listResult;

        } else if (returnType.isArray() && byte[].class != returnType) {
            Object array = Array.newInstance(returnType.getComponentType(), sizeResult);
            if (returnType.getComponentType().isPrimitive()) {
                int len = listResult.size();
                for (int i = 0; i < len; i++) {
                    Array.set(array, i, listResult.get(i));
                }
            } else {
                listResult.toArray((Object[]) array);
            }
            return array;

        } else if (Map.class.isAssignableFrom(returnType)) {
            //   KeyValuePair ??  Map 
            // entry.key?nullHashMap
            Map<Object, Object> map;
            if (returnType.isAssignableFrom(HashMap.class)) {

                map = new HashMap<Object, Object>(listResult.size() * 2);

            } else if (returnType.isAssignableFrom(Hashtable.class)) {

                map = new Hashtable<Object, Object>(listResult.size() * 2);

            } else {

                throw new Error(returnType.toString());
            }
            for (Object obj : listResult) {
                if (obj == null) {
                    continue;
                }

                Map.Entry<?, ?> entry = (Map.Entry<?, ?>) obj;

                if (map.getClass() == Hashtable.class && entry.getKey() == null) {
                    continue;
                }

                map.put(entry.getKey(), entry.getValue());
            }

            return map;

        } else if (returnType.isAssignableFrom(HashSet.class)) {

            //   Set ?
            return new HashSet<Object>(listResult);

        } else {

            if (sizeResult == 1) {
                // ?  Bean?Boolean
                return listResult.get(0);

            } else if (sizeResult == 0) {

                // null
                if (returnType.isPrimitive()) {
                    String msg = "Incorrect result size: expected 1, actual " + sizeResult + ": "
                            + runtime.getMetaData();
                    throw new EmptyResultDataAccessException(msg, 1);
                } else {
                    return null;
                }

            } else {
                // IncorrectResultSizeDataAccessException
                String msg = "Incorrect result size: expected 0 or 1, actual " + sizeResult + ": "
                        + runtime.getMetaData();
                throw new IncorrectResultSizeDataAccessException(msg, 1, sizeResult);
            }
        }
    }
    return listResult;
}

From source file:com.replaymod.replaystudio.collection.PacketList.java

@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
    if (a.length < size) {
        a = (T[]) Array.newInstance(a.getClass().getComponentType(), size);
    }/*  w  ww  . j  a  va2  s  .  com*/
    ListEntry e = first;
    for (int i = 0; i < a.length; i++) {
        if (e != null) {
            a[i] = (T) e.data;
            e = e.next;
        } else {
            a[i] = null;
        }
    }
    return a;
}

From source file:net.navasoft.madcoin.backend.services.rest.impl.BusinessService.java

/**
 * Gets the all./*from w  w w .ja v a2 s.com*/
 * 
 * @return the all
 * @since 1/09/2014, 10:52:57 PM
 */
@Override
public SuccessResponseVO getAll() {
    BusinessSuccessResponseVO response = new AppAllBusinessLinesSuccessResponseVO();
    List<BusinessLines> total = dao.getAll();
    if (!total.isEmpty()) {
        BusinessLines[] totalLOB = (BusinessLines[]) Array.newInstance(BusinessLines.class, total.size());
        response.setBusinessLines(total.toArray(totalLOB));
        return response;
    } else {
        throw ControllerExceptionFactory.createException(InsufficientLOBException.class.getCanonicalName(), 1);
    }
}

From source file:HashSet.java

@SuppressWarnings("unchecked")
@Override// w w  w  . j  av a  2  s  .c  om
public <T> T[] toArray(T[] a) {
    if (a.length < size) {
        a = (T[]) Array.newInstance(a.getClass().getComponentType(), size);
    }
    int index = 0;
    for (int i = 0; i < table.length; ++i) {
        Object e = table[i];
        if (e != null) {
            a[index++] = (T) unmaskNull(e);
        }
    }
    while (index < a.length) {
        a[index++] = null;
    }
    return a;
}

From source file:Main.java

@SuppressWarnings("unchecked")
public static <T> T[] subArray(T[] array, int[] indexs) {
    if (array == null || array.length == 0) {
        return array;
    }/*from w w w  .j a  v  a  2  s .  c  om*/
    if (indexs == null || indexs.length == 0) {
        return (T[]) Array.newInstance(array.getClass().getComponentType(), 0);
    }
    int len = array.length;
    T[] sub = (T[]) Array.newInstance(array.getClass().getComponentType(), indexs.length);
    for (int i = 0; i < indexs.length; i++) {
        int index = indexs[i];
        if (index < 0) {
            index = len + index;
        }
        if (index >= 0 && index < len) {
            sub[i] = array[index];
        }
    }
    return sub;
}

From source file:net.sourceforge.jaulp.lang.ObjectUtils.java

/**
 * Try to clone the given object./*from  w ww .  j  a v  a 2s . c  o m*/
 *
 * @param object
 *            The object to clone.
 * @return The cloned object or null if the clone process failed.
 * @throws NoSuchMethodException
 *             the no such method exception
 * @throws SecurityException
 *             Thrown if the security manager indicates a security violation.
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws IllegalArgumentException
 *             the illegal argument exception
 * @throws InvocationTargetException
 *             the invocation target exception
 * @throws ClassNotFoundException
 *             the class not found exception
 * @throws InstantiationException
 *             the instantiation exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Object cloneObject(final Object object)
        throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, ClassNotFoundException, InstantiationException, IOException {
    Object clone = null;
    // Try to clone the object if it implements Serializable.
    if (object instanceof Serializable) {
        clone = SerializedObjectUtils.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;
            }
        }
        Class<?> clazz = object.getClass();
        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 = ReflectionUtils.getNewInstance(object);
        BeanUtils.copyProperties(clone, object);
    }
    return clone;
}

From source file:com.metaparadigm.jsonrpc.ArraySerializer.java

public Object unmarshall(SerializerState state, Class clazz, Object o) throws UnmarshallException {
    JSONArray jso = (JSONArray) o;//ww  w  .  j av a2 s.c o  m
    Class cc = clazz.getComponentType();
    int i = 0;
    try {
        if (clazz == int[].class) {
            int arr[] = new int[jso.length()];
            for (; i < jso.length(); i++)
                arr[i] = ((Number) ser.unmarshall(state, cc, jso.get(i))).intValue();
            return arr;
        } else if (clazz == byte[].class) {
            byte arr[] = new byte[jso.length()];
            for (; i < jso.length(); i++)
                arr[i] = ((Number) ser.unmarshall(state, cc, jso.get(i))).byteValue();
            return arr;
        } else if (clazz == short[].class) {
            short arr[] = new short[jso.length()];
            for (; i < jso.length(); i++)
                arr[i] = ((Number) ser.unmarshall(state, cc, jso.get(i))).shortValue();
            return arr;
        } else if (clazz == long[].class) {
            long arr[] = new long[jso.length()];
            for (; i < jso.length(); i++)
                arr[i] = ((Number) ser.unmarshall(state, cc, jso.get(i))).longValue();
            return arr;
        } else if (clazz == float[].class) {
            float arr[] = new float[jso.length()];
            for (; i < jso.length(); i++)
                arr[i] = ((Number) ser.unmarshall(state, cc, jso.get(i))).floatValue();
            return arr;
        } else if (clazz == double[].class) {
            double arr[] = new double[jso.length()];
            for (; i < jso.length(); i++)
                arr[i] = ((Number) ser.unmarshall(state, cc, jso.get(i))).doubleValue();
            return arr;
        } else if (clazz == char[].class) {
            char arr[] = new char[jso.length()];
            for (; i < jso.length(); i++)
                arr[i] = ((String) ser.unmarshall(state, cc, jso.get(i))).charAt(0);
            return arr;
        } else if (clazz == boolean[].class) {
            boolean arr[] = new boolean[jso.length()];
            for (; i < jso.length(); i++)
                arr[i] = ((Boolean) ser.unmarshall(state, cc, jso.get(i))).booleanValue();
            return arr;
        } else {
            Object arr[] = (Object[]) Array.newInstance(clazz.getComponentType(), jso.length());
            for (; i < jso.length(); i++)
                arr[i] = ser.unmarshall(state, cc, jso.get(i));
            return arr;
        }
    } catch (UnmarshallException e) {
        throw new UnmarshallException("element " + i + " " + e.getMessage());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
}

From source file:com.cloudera.oryx.ml.serving.als.model.ALSServingModel.java

/**
 * Creates an empty model./*from  w  w w .j  av a  2s.  co  m*/
 *
 * @param features number of features expected for user/item feature vectors
 * @param implicit whether model implements implicit feedback
 */
@SuppressWarnings("unchecked")
ALSServingModel(int features, boolean implicit) {
    Preconditions.checkArgument(features > 0);

    X = HashObjObjMaps.newMutableMap();
    Y = (ObjObjMap<String, float[]>[]) Array.newInstance(ObjObjMap.class, PARTITIONS);
    for (int i = 0; i < Y.length; i++) {
        Y[i] = HashObjObjMaps.newMutableMap();
    }

    recentNewUsers = new HashSet<>();
    recentNewItems = (Collection<String>[]) Array.newInstance(HashSet.class, PARTITIONS);
    for (int i = 0; i < recentNewItems.length; i++) {
        recentNewItems[i] = new HashSet<>();
    }

    knownItems = HashObjObjMaps.newMutableMap();

    xLock = new ReentrantReadWriteLock();
    yLocks = new ReentrantReadWriteLock[Y.length];
    for (int i = 0; i < yLocks.length; i++) {
        yLocks[i] = new ReentrantReadWriteLock();
    }

    this.features = features;
    this.implicit = implicit;
}

From source file:de.tuberlin.uebb.jbop.optimizer.array.LocalArrayLengthInliner.java

/**
 * Registers values for local arrays that are created via NEWARRAY / ANEWARRAY or MULTIANEWARRAY.
 * /*w  w  w.  j a va2s.  c o m*/
 * @param currentNode
 *          the current node
 * @param knownArrays
 *          the known arrays
 * @return true, if successful
 */
@Override
protected int registerAdditionalValues(final AbstractInsnNode currentNode, //
        final Map<Integer, Object> knownArrays) {
    final int opcode = currentNode.getOpcode();
    if (!((opcode == Opcodes.NEWARRAY) || (opcode == Opcodes.ANEWARRAY)
            || (opcode == Opcodes.MULTIANEWARRAY))) {
        return 0;
    }
    int dims = 1;
    if (currentNode.getOpcode() == Opcodes.MULTIANEWARRAY) {
        final MultiANewArrayInsnNode node = (MultiANewArrayInsnNode) currentNode;
        dims = node.dims;
    }
    final int sizes[] = new int[dims];
    AbstractInsnNode previous = currentNode;
    for (int i = 0; i < dims; ++i) {
        previous = NodeHelper.getPrevious(previous);
        if (!NodeHelper.isIntNode(previous)) {
            return 0;
        }
        try {
            final int value = NodeHelper.getNumberValue(previous).intValue();
            sizes[i] = value;
        } catch (final NotANumberException nane) {
            return 0;
        }
    }
    final AbstractInsnNode next = NodeHelper.getNext(currentNode);
    if (!(next instanceof VarInsnNode)) {
        return 0;
    }
    final int index = ((VarInsnNode) next).var;
    knownArrays.put(Integer.valueOf(index), Array.newInstance(Object.class, sizes));
    return 2;
}