Java Class New Instance newInstance(Class elementType, int len)

Here you can find the source of newInstance(Class elementType, int len)

Description

Constructs a new array of the given non-primitive component type and length.

License

Apache License

Parameter

Parameter Description
elementType the type of elements in the new array
len the length, or capacity, of the new array

Return

a new array with the given component type and length, initially filled with all null s.

Declaration

public static <T> T[] newInstance(Class<T> elementType, int len) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.Array;

public class Main {
    /**/*  w  w  w.ja  v  a  2 s . c o m*/
     * Constructs a new array of the given <em>non-primitive</em> component type and length. This is
     * a convenient wrapper around {@link Array#newInstance(Class, int)} that provides a more useful
     * return type for reference component types: no cast required.
     *
     * @param elementType the type of elements in the new array
     * @param len the length, or capacity, of the new array
     * @return a new array with the given component type and length, initially filled with all
     *       {@code null}s.
     */
    public static <T> T[] newInstance(Class<T> elementType, int len) {
        if (elementType.isPrimitive()) {
            throw new IllegalArgumentException("element type cannot be primitive: " + elementType);
        }
        @SuppressWarnings("unchecked")
        T ret[] = (T[]) Array.newInstance(elementType, len);
        return ret;
    }
}

Related

  1. newInstance(Class cls)
  2. newInstance(Class cls)
  3. newInstance(Class cls, Object... args)
  4. newInstance(Class clz, Class argType, K arg)
  5. newInstance(Class componentType, int size)
  6. newInstance(Class klass)
  7. newInstance(Class klass)
  8. newInstance(Class klass)
  9. newInstance(Class klass)