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:Utils.java

/**
 * This methods load a class given the classloader and the name of the class, and work for
 * extended names of primitive types. <p>
 * If you try to do ClassLoader.loadClass("boolean") it barfs it cannot find the class,
 * so this method cope with this problem.
 *//* w ww  .  j a  v  a  2s  .c om*/
public static Class loadClass(ClassLoader loader, String name) throws ClassNotFoundException {
    if (name == null)
        throw new ClassNotFoundException("null");

    name = name.trim();
    if (name.equals("boolean"))
        return boolean.class;
    else if (name.equals("byte"))
        return byte.class;
    else if (name.equals("char"))
        return char.class;
    else if (name.equals("short"))
        return short.class;
    else if (name.equals("int"))
        return int.class;
    else if (name.equals("long"))
        return long.class;
    else if (name.equals("float"))
        return float.class;
    else if (name.equals("double"))
        return double.class;
    else if (name.equals("java.lang.String"))
        return String.class;
    else if (name.equals("java.lang.Object"))
        return Object.class;
    else if (name.startsWith("[")) {
        // It's an array, figure out how many dimensions
        int dimension = 0;
        while (name.charAt(dimension) == '[') {
            ++dimension;
        }
        char type = name.charAt(dimension);
        Class cls = null;
        switch (type) {
        case 'Z':
            cls = boolean.class;
            break;
        case 'B':
            cls = byte.class;
            break;
        case 'C':
            cls = char.class;
            break;
        case 'S':
            cls = short.class;
            break;
        case 'I':
            cls = int.class;
            break;
        case 'J':
            cls = long.class;
            break;
        case 'F':
            cls = float.class;
            break;
        case 'D':
            cls = double.class;
            break;
        case 'L':
            // Strip the semicolon at the end
            String n = name.substring(dimension + 1, name.length() - 1);
            cls = loadClass(loader, n);
            break;
        }

        if (cls == null) {
            throw new ClassNotFoundException(name);
        } else {
            int[] dim = new int[dimension];
            return Array.newInstance(cls, dim).getClass();
        }
    } else {
        if (loader != null)
            return loader.loadClass(name);
        else
            return Class.forName(name, false, null);
    }
}

From source file:com.alibaba.doris.admin.service.impl.ValueParseUtil.java

/**
 * ?String ?://ww w  .  ja  va  2s .  c  o m
 * 
 * <pre>
 * short, int, long, float : 0
 * char, byte: 0
 * String: null
 * Map, List: null
 * Integer, Long, Float : null
 * Date: null
 * array: null
 * </pre>
 * 
 * @param strValue
 * @param clazz
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> T parseStringValue(String strValue, Class<T> clazz, boolean autoDefault) {

    if (DEF_NULL.equals(strValue)) {
        if (!clazz.isPrimitive()) {
            return null;
        }
        if (autoDefault) {
            return (T) getInternalDefaultValue(clazz);
        } else {
            return null;
        }
    }

    if (DEF_EMPTY.equals(strValue)) {
        if (clazz.isArray()) {
            return (T) Array.newInstance(clazz.getComponentType(), 0);
        }

        if (Map.class.isAssignableFrom(clazz)) {
            return (T) Collections.EMPTY_MAP;
        }

        if (List.class.isAssignableFrom(clazz)) {
            return (T) new ArrayList<Object>();
        }

        if (Set.class.isAssignableFrom(clazz)) {
            return (T) new HashSet<Object>();
        }

        if (String.class.equals(clazz)) {
            return (T) StringUtils.EMPTY;
        }

        if (Character.TYPE.equals(clazz) || Character.class.equals(clazz)) {
            return (T) Character.valueOf(' ');
        }

        if (autoDefault) {
            return (T) getInternalDefaultValue(clazz);
        } else {
            return null;
        }
    }

    if (StringUtils.isBlank(strValue)) {// ?
        if (autoDefault) {
            return (T) getInternalDefaultValue(clazz);
        } else {
            return null;
        }
    } else {

        if (String.class.equals(clazz)) {
            return (T) strValue;
        }

        if (Short.TYPE.equals(clazz) || Short.class.equals(clazz)) {
            return (T) Short.valueOf(strValue);
        }

        if (Integer.TYPE.equals(clazz) || Integer.class.equals(clazz)) {
            return (T) Integer.valueOf(strValue);
        }
        if (Long.TYPE.equals(clazz) || Long.class.equals(clazz)) {
            return (T) Long.valueOf(strValue);
        }
        if (Boolean.TYPE.equals(clazz) || Boolean.class.equals(clazz)) {
            return (T) Boolean.valueOf(strValue);
        }
        if (Float.TYPE.equals(clazz) || Float.class.equals(clazz)) {
            return (T) Float.valueOf(strValue);
        }
        if (Double.TYPE.equals(clazz) || Double.class.equals(clazz)) {
            return (T) Double.valueOf(strValue);
        }
        if (Byte.TYPE.equals(clazz) || Byte.class.equals(clazz)) {
            return (T) Byte.valueOf(strValue);
        }
        if (Character.TYPE.equals(clazz) || Character.class.equals(clazz)) {
            return (T) Character.valueOf(strValue.charAt(0));
        }

        if (clazz.isArray()) {
            final Class<?> componentType = clazz.getComponentType();
            // String[]
            if (String.class.equals(componentType)) {
                return (T) StringUtils.split(strValue, ',');
            }
            // ?char[]
            if (Character.TYPE.equals(componentType)) {
                return (T) strValue.toCharArray();
            }

            if (Character.class.equals(componentType)) {
                final char[] tmp = strValue.toCharArray();
                final Character[] result = new Character[tmp.length];
                for (int i = 0; i < result.length; i++) {
                    result[i] = tmp[i];
                }
                return (T) result;
            }

            if (Byte.TYPE.equals(componentType) || Byte.class.equals(componentType)) {
                return (T) (strValue == null ? null : strValue.getBytes());
            }
        }
    }

    return null;

}

From source file:com.l2jserver.util.transformer.impl.ArrayTransformer.java

@Override
@SuppressWarnings("unchecked")
public T[] untransform(Class<? extends T[]> type, String stringValue) {
    final Transformer<T> transformer = (Transformer<T>) TransformerFactory
            .getTransfromer(type.getComponentType());
    final String[] stringValues = StringUtils.split(stringValue, '|');
    final Object values = Array.newInstance(type.getComponentType(), stringValues.length);
    int i = 0;//from   w w  w  .j a v  a 2s.c  o  m
    for (final String value : stringValues) {
        Array.set(values, i++, transformer.untransform((Class<T>) type.getComponentType(), value));
    }

    return type.cast(values);
}

From source file:Main.java

/**
 * Returns a copy of the given array of size 1 greater than the argument. 
 * The last value of the array is left to the default value.
 * // w  w w  .j  a v  a2s.  c o m
 * @param array The array to copy, must not be <code>null</code>.
 * @param newArrayComponentType If <code>array</code> is <code>null</code>, create a 
 * size 1 array of this type.
 * @return A new copy of the array of size 1 greater than the input.
 */
private static Object copyArrayGrow1(Object array, Class newArrayComponentType) {
    if (array != null) {
        int arrayLength = Array.getLength(array);
        Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);
        System.arraycopy(array, 0, newArray, 0, arrayLength);
        return newArray;
    }
    return Array.newInstance(newArrayComponentType, 1);
}

From source file:org.atemsource.atem.impl.common.attribute.collection.ArrayAttributeImpl.java

@Override
protected Class<Object> createEmptyCollection() {
    return (Class<Object>) Array.newInstance(getTargetType().getJavaType(), 0);
}

From source file:net.radai.beanz.codecs.ArrayCodec.java

@Override
public Object decode(String encoded) {
    if (encoded == null || (encoded = encoded.trim()).isEmpty()) {
        return null;
    }//from   w w  w. jav a  2 s . c  om
    if (!(encoded.startsWith("[") && encoded.endsWith("]"))) {
        throw new IllegalArgumentException();
    }
    String[] elements = encoded.substring(1, encoded.length() - 1).split("\\s*,\\s*");
    Class<?> erased = erase(getElementType());
    Object array = Array.newInstance(erased, elements.length);
    for (int i = 0; i < elements.length; i++) {
        Array.set(array, i, elementCodec.decode(elements[i]));
    }
    return array;
}

From source file:it.nicola_amatucci.util.Json.java

public static <T> T object_from_json(JSONObject json, Class<T> objClass) throws Exception {
    T t = null;/*  ww w . ja  v a  2s .c  om*/
    Object o = null;

    try {
        //create new object instance
        t = objClass.newInstance();

        //object fields
        Field[] fields = objClass.getFields();

        for (Field field : fields) {
            //field name
            o = json.get(field.getName());

            if (o.equals(null))
                continue;

            //field value
            try {
                String typeName = field.getType().getSimpleName();

                if (typeName.equals("String")) {
                    o = json.getString(field.getName()); //String
                } else if (typeName.equals("boolean")) {
                    o = Integer.valueOf(json.getInt(field.getName())); //boolean
                } else if (typeName.equals("int")) {
                    o = Integer.valueOf(json.getInt(field.getName())); //int
                } else if (typeName.equals("long")) {
                    o = Long.valueOf(json.getLong(field.getName())); //long                  
                } else if (typeName.equals("double")) {
                    o = Double.valueOf(json.getDouble(field.getName())); //double
                } else if (typeName.equals("Date")) {
                    o = new SimpleDateFormat(Json.DATA_FORMAT).parse(o.toString()); //data
                } else if (field.getType().isArray()) {
                    JSONArray arrayJSON = new JSONArray(o.toString());
                    T[] arrayOfT = (T[]) null;

                    try {
                        //create object array
                        Class c = Class.forName(field.getType().getName()).getComponentType();
                        arrayOfT = (T[]) Array.newInstance(c, arrayJSON.length());

                        //parse objects                  
                        for (int i = 0; i < json.length(); i++)
                            arrayOfT[i] = (T) object_from_json(arrayJSON.getJSONObject(i), c);
                    } catch (Exception e) {
                        throw e;
                    }

                    o = arrayOfT;
                } else {
                    o = object_from_json(new JSONObject(o.toString()), field.getType()); //object
                }

            } catch (Exception e) {
                throw e;
            }

            t.getClass().getField(field.getName()).set(t, o);
        }

    } catch (Exception e) {
        throw e;
    }

    return t;
}

From source file:Main.java

/**
 * Create new {@link Iterable} object which combine the first and the second
 * parameters./*  w w  w .j  a v  a2  s  .co  m*/
 * 
 * @param <T>
 *            Type of the items in the array of the first specified
 *            parameter, this type also specify the type of the arrays of
 *            the which will be returned by the returned {@link Iterable}
 * @param <E>
 *            Type of the second {@link Iterable} arrays. It may be the same
 *            type as the first {@link Iterable}, or array of any other
 *            subclass
 * @param firstIterable
 *            {@link Iterable}, the first {@link Iterable} which contains
 *            items
 * @param secondIterable
 *            {@link Iterable}, the second {@link Iterable} which contains
 *            items
 * @return {@link Iterable}, object which will return {@link Iterator}s
 *         which will iterate over the second {@link Iterable} parameter as
 *         many times as there are items in the first {@link Iterable}
 *         parameter. The returned arrays will contains every possible
 *         combination between items in the first {@link Iterable}, and the
 *         second {@link Iterable}. For example: if the first
 *         {@link Iterable} contains <code>{1, 2}</code> and the second
 *         {@link Iterable} contains <code>{'a', 'b', 'c'}</code> the
 *         returned {@link Iterable} object will dynamically combine the
 *         {@link Iterable}s and provide following combination in specified
 *         order:
 *         <code>{1, 'a'}, {1, 'b'}, {1, 'c'}, {2, 'a'}, {2, 'b'}, {2, 'c'}</code>
 */
public static <T, E extends T> Iterable<T[]> combineIterables(final Iterable<T[]> firstIterable,
        final Iterable<E[]> secondIterable) {
    return new Iterable<T[]>() {

        /**
         * {@inheritDoc}
         */
        public Iterator<T[]> iterator() {

            return new Iterator<T[]>() {
                private Iterator<T[]> firstArrayIterator = firstIterable.iterator();
                private final Iterator<E[]> secondArrayIterator = secondIterable.iterator();
                private T[] appendArray = secondArrayIterator.next();

                /**
                 * {@inheritDoc}
                 */
                public boolean hasNext() {
                    return firstArrayIterator.hasNext() || secondArrayIterator.hasNext();
                }

                /**
                 * {@inheritDoc}
                 */
                public T[] next() {
                    if (!hasNext()) {
                        throw new NoSuchElementException();
                    }
                    if (!firstArrayIterator.hasNext()) {
                        firstArrayIterator = firstIterable.iterator();
                        appendArray = secondArrayIterator.next();
                    }
                    T[] streamsItem = firstArrayIterator.next();
                    @SuppressWarnings("unchecked")
                    T[] result = (T[]) Array.newInstance(streamsItem.getClass().getComponentType(),
                            streamsItem.length + appendArray.length);
                    System.arraycopy(streamsItem, 0, result, 0, streamsItem.length);
                    System.arraycopy(appendArray, 0, result, streamsItem.length, appendArray.length);
                    return result;
                }

                /**
                 * {@inheritDoc}
                 */
                public void remove() {
                    throw new UnsupportedOperationException();
                }

            };
        }
    };
}

From source file:jp.furplag.util.commons.ObjectUtils.java

/**
 * substitute for {@link java.lang.Class#newInstance()}.
 *
 * @param type the Class object, return false if null.
 * @return empty instance of specified {@link java.lang.Class}.
 * @throws IllegalArgumentException// w  w  w .j  av a2  s  .c  o  m
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws ClassNotFoundException
 * @throws NegativeArraySizeException
 */
@SuppressWarnings("unchecked")
public static <T> T newInstance(final Class<T> type) throws InstantiationException {
    if (type == null)
        return null;
    if (type.isArray())
        return (T) Array.newInstance(type.getComponentType(), 0);
    if (Void.class.equals(ClassUtils.primitiveToWrapper(type))) {
        try {
            Constructor<Void> c = Void.class.getDeclaredConstructor();
            c.setAccessible(true);

            return (T) c.newInstance();
        } catch (SecurityException e) {
        } catch (NoSuchMethodException e) {
        } catch (InvocationTargetException e) {
        } catch (IllegalAccessException e) {
        }

        return null;
    }

    if (type.isInterface()) {
        if (!Collection.class.isAssignableFrom(type))
            throw new InstantiationException(
                    "could not create instance, the type \"" + type.getName() + "\" is an interface.");
        if (List.class.isAssignableFrom(type))
            return (T) Lists.newArrayList();
        if (Map.class.isAssignableFrom(type))
            return (T) Maps.newHashMap();
        if (Set.class.isAssignableFrom(type))
            return (T) Sets.newHashSet();
    }

    if (type.isPrimitive()) {
        if (boolean.class.equals(type))
            return (T) Boolean.FALSE;
        if (char.class.equals(type))
            return (T) Character.valueOf(Character.MIN_VALUE);

        return (T) NumberUtils.valueOf("0", (Class<? extends Number>) type);
    }
    if (ClassUtils.isPrimitiveOrWrapper(type))
        return null;
    if (Modifier.isAbstract(type.getModifiers()))
        throw new InstantiationException(
                "could not create instance, the type \"" + type.getName() + "\" is an abstract class.");

    try {
        Constructor<?> c = type.getDeclaredConstructor();
        c.setAccessible(true);

        return (T) c.newInstance();
    } catch (SecurityException e) {
    } catch (NoSuchMethodException e) {
    } catch (InvocationTargetException e) {
    } catch (IllegalAccessException e) {
    }

    throw new InstantiationException("could not create instance, the default constructor of \"" + type.getName()
            + "()\" is not accessible ( or undefined ).");
}

From source file:com.laxser.blitz.lama.core.SelectOperation.java

@Override
public Object execute(Map<String, Object> parameters) {
    // //from  w w  w.java  2  s .com
    List<?> listResult = dataAccess.select(sql, modifier, parameters, 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 + ": "
                        + modifier.toString();
                throw new EmptyResultDataAccessException(msg, 1);
            } else {
                return null;
            }

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