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:se.vgregion.dao.domain.patterns.repository.db.jpa.AbstractJpaRepository.java

/**
 * Get the underlying class for a type, or null if the type is a variable type.
 * //from   ww w  . j a  v a2  s .c o m
 * @param type
 *            the type
 * @return the underlying class
 */
@SuppressWarnings("unchecked")
private Class<? extends T> getClass(Type type) {
    if (type instanceof Class) {
        return (Class<? extends T>) type;
    } else if (type instanceof ParameterizedType) {
        return getClass(((ParameterizedType) type).getRawType());
    } else if (type instanceof GenericArrayType) {
        Type componentType = ((GenericArrayType) type).getGenericComponentType();
        Class<? extends T> componentClass = getClass(componentType);
        if (componentClass != null) {
            return (Class<? extends T>) Array.newInstance(componentClass, 0).getClass();
        } else {
            return null;
        }
    } else {
        return null;
    }
}

From source file:com.opengamma.analytics.math.curve.ObjectsCurve.java

/**
 * //ww  w  .  j a  va  2  s.com
 * @param data A set of <i>x-y</i> pairs, not null
 * @param isSorted Is the <i>x</i>-data sorted
 */
public ObjectsCurve(final Set<Pair<T, U>> data, final boolean isSorted) {
    super();
    ArgumentChecker.notNull(data, "data");
    _n = data.size();
    final List<T> xTemp = new ArrayList<>(_n);
    final List<U> yTemp = new ArrayList<>(_n);
    for (final Pair<T, U> entry : data) {
        ArgumentChecker.notNull(entry, "element of data");
        xTemp.add(entry.getFirst());
        yTemp.add(entry.getSecond());
    }
    final Pair<T, U> firstEntry = data.iterator().next();
    _xData = xTemp.toArray((T[]) Array.newInstance(firstEntry.getFirst().getClass(), 0));
    _yData = yTemp.toArray((U[]) Array.newInstance(firstEntry.getSecond().getClass(), 0));
    if (!isSorted) {
        ParallelArrayBinarySort.parallelBinarySort(_xData, _yData);
    }
}

From source file:com.adobe.acs.commons.util.impl.ValueMapTypeConverter.java

private Object handleListType(ParameterizedType pType) {
    Class<?> genericParameter = getGenericParameter(pType);
    Object array = getValueFromMap(Array.newInstance(genericParameter, 0).getClass());
    if (array == null) {
        return null;
    }/*  ww w . java2 s.c o  m*/
    return Arrays.asList((Object[]) array);
}

From source file:net.navasoft.madcoin.backend.services.vo.response.impl.AuthenticationFailedResponseVO.java

/**
 * Gets the causes.//from  w w w.  ja  va2s . com
 * 
 * @return the causes
 * @since 28/07/2014, 10:51:01 PM
 */
@Override
@JsonIgnore
public Object[] getCauses() {
    Object[] causes = (Object[]) Array.newInstance(Object.class, 0);
    causes = ArrayUtils.add(causes, failedUser);
    causes = ArrayUtils.add(causes, failedUserType);
    causes = ArrayUtils.add(causes, additionalMessage);
    return causes;
}

From source file:Main.java

/**
 * convert value to given type./*from  ww  w .j  ava  2 s.co m*/
 * null safe.
 *
 * @param value value for convert
 * @param type  will converted type
 * @return value while converted
 */
public static Object convertCompatibleType(Object value, Class<?> type) {

    if (value == null || type == null || type.isAssignableFrom(value.getClass())) {
        return value;
    }
    if (value instanceof String) {
        String string = (String) value;
        if (char.class.equals(type) || Character.class.equals(type)) {
            if (string.length() != 1) {
                throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!"
                        + " when convert String to char, the String MUST only 1 char.", string));
            }
            return string.charAt(0);
        } else if (type.isEnum()) {
            return Enum.valueOf((Class<Enum>) type, string);
        } else if (type == BigInteger.class) {
            return new BigInteger(string);
        } else if (type == BigDecimal.class) {
            return new BigDecimal(string);
        } else if (type == Short.class || type == short.class) {
            return Short.valueOf(string);
        } else if (type == Integer.class || type == int.class) {
            return Integer.valueOf(string);
        } else if (type == Long.class || type == long.class) {
            return Long.valueOf(string);
        } else if (type == Double.class || type == double.class) {
            return Double.valueOf(string);
        } else if (type == Float.class || type == float.class) {
            return Float.valueOf(string);
        } else if (type == Byte.class || type == byte.class) {
            return Byte.valueOf(string);
        } else if (type == Boolean.class || type == boolean.class) {
            return Boolean.valueOf(string);
        } else if (type == Date.class) {
            try {
                return new SimpleDateFormat(DATE_FORMAT).parse((String) value);
            } catch (ParseException e) {
                throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT
                        + ", cause: " + e.getMessage(), e);
            }
        } else if (type == Class.class) {
            return forName((String) value);
        }
    } else if (value instanceof Number) {
        Number number = (Number) value;
        if (type == byte.class || type == Byte.class) {
            return number.byteValue();
        } else if (type == short.class || type == Short.class) {
            return number.shortValue();
        } else if (type == int.class || type == Integer.class) {
            return number.intValue();
        } else if (type == long.class || type == Long.class) {
            return number.longValue();
        } else if (type == float.class || type == Float.class) {
            return number.floatValue();
        } else if (type == double.class || type == Double.class) {
            return number.doubleValue();
        } else if (type == BigInteger.class) {
            return BigInteger.valueOf(number.longValue());
        } else if (type == BigDecimal.class) {
            return BigDecimal.valueOf(number.doubleValue());
        } else if (type == Date.class) {
            return new Date(number.longValue());
        }
    } else if (value instanceof Collection) {
        Collection collection = (Collection) value;
        if (type.isArray()) {
            int length = collection.size();
            Object array = Array.newInstance(type.getComponentType(), length);
            int i = 0;
            for (Object item : collection) {
                Array.set(array, i++, item);
            }
            return array;
        } else if (!type.isInterface()) {
            try {
                Collection result = (Collection) type.newInstance();
                result.addAll(collection);
                return result;
            } catch (Throwable e) {
                e.printStackTrace();
            }
        } else if (type == List.class) {
            return new ArrayList<>(collection);
        } else if (type == Set.class) {
            return new HashSet<>(collection);
        }
    } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) {
        Collection collection;
        if (!type.isInterface()) {
            try {
                collection = (Collection) type.newInstance();
            } catch (Throwable e) {
                collection = new ArrayList<>();
            }
        } else if (type == Set.class) {
            collection = new HashSet<>();
        } else {
            collection = new ArrayList<>();
        }
        int length = Array.getLength(value);
        for (int i = 0; i < length; i++) {
            collection.add(Array.get(value, i));
        }
        return collection;
    }
    return value;
}

From source file:com.anhth12.lambda.app.serving.als.model.ALSServingModel.java

ALSServingModel(int features, boolean implicit, RescorerProvider rescoreProvider) {
    Preconditions.checkArgument(features > 0);

    X = HashObjObjMaps.newMutableMap();/*from   ww w  . j a  va  2  s .  c om*/
    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 ReadWriteLock[Y.length];
    for (int i = 0; i < yLocks.length; i++) {
        yLocks[i] = new ReentrantReadWriteLock();
    }

    this.features = features;
    this.implicit = implicit;
    this.rescorerProvider = rescoreProvider;
}

From source file:com.fengduo.bee.commons.core.lang.ArrayUtils.java

/**
 * <pre>//from   w ww  .jav  a 2 s  .  c  o m
 *      ?? 
 *      ?index??index? [-1,length]
 *      ?indexlength
 * </pre>
 */
@SuppressWarnings("unchecked")
public static <T extends Object> T[] add(T[] array, int index, T newValue) {
    int length = array == null ? 0 : array.length;
    index = Math.max(0, index);
    index = Math.min(length, index);
    Class<?> clazz = array == null ? newValue.getClass() : array.getClass().getComponentType();
    T[] newInstance = (T[]) Array.newInstance(clazz, length + 1);

    for (int i = 0, j = 0; i < newInstance.length;) {
        T _value = i == index ? newValue : array[j++];
        newInstance[i++] = _value;
    }
    return newInstance;
}

From source file:jef.tools.ArrayUtils.java

/**
 * ??//from  ww w.  ja  v  a 2  s . c om
 * 
 * @param from
 * @param to
 * @return
 */
@SuppressWarnings("unchecked")
public static <S, T> T[] cast(S[] from, Class<T> to) {
    T[] result = (T[]) Array.newInstance(to, from.length);
    for (int i = 0; i < result.length; i++) {
        result[i] = (T) from[i];
    }
    return result;
}

From source file:Main.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static Object toObjectArray(Class<?> type, Collection collection) {
    return collection.toArray((Object[]) Array.newInstance(type, collection.size()));
}

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

/**
 * Returns all parents of node which are of given class type ordered from
 * root to parent of node.//from  w ww . java 2 s .com
 */
public <E extends Node> E[] getParents(final Class<E> clazz) {
    return (E[]) Stream.of(getParents()).filter($node -> clazz.isAssignableFrom($node.getClass()))
            .toArray($size -> (E[]) Array.newInstance(clazz, $size));
}