Example usage for java.lang Class getComponentType

List of usage examples for java.lang Class getComponentType

Introduction

In this page you can find the example usage for java.lang Class getComponentType.

Prototype

public Class<?> getComponentType() 

Source Link

Document

Returns the Class representing the component type of an array.

Usage

From source file:edu.umich.flowfence.common.QMDescriptor.java

private static List<String> toNames(Class<?>... classes) {
    if (!ParceledPayload.canParcelTypes(classes)) {
        throw new ParcelFormatException("Can't parcel arguments");
    }//from  w  w w  .  j  a  v  a2s .c o  m
    // ClassUtils.classesTaClassNames doesn't work here, because it emits arrays
    // in their JNI form ([Ljava.lang.String;). Handle array type conversion manually.
    List<String> classNames = new ArrayList<>(classes.length);
    for (Class<?> clazz : classes) {
        int arrayDepth = 0;
        while (clazz.isArray()) {
            arrayDepth++;
            clazz = clazz.getComponentType();
        }
        classNames.add(clazz.getName() + StringUtils.repeat("[]", arrayDepth));
    }
    return classNames;
}

From source file:Main.java

private static <T, U> T[] copyOfRange(final U[] original, final int from, final int to,
        final Class<? extends T[]> newType) {
    final int newLength = to - from;
    if (newLength < 0) {
        throw new IllegalArgumentException(from + " > " + to);
    }//from w ww.j  a va 2s .  c om
    final T[] copy = ((Object) newType == (Object) Object[].class) ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
    System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength));
    return copy;
}

From source file:de.bund.bva.pliscommon.serviceapi.core.serviceimpl.MappingHelper.java

/**
 * Bildet ein Objekt mithilfe von Dozer auf einen gewnschten Zieltyp ab. Im Gegensatz zu
 * {@link Mapper#map(Object, Class)} knnen als Zieltyp auch generische Collections, String und primitive
 * Typen bergeben werden./*  w w  w  .  ja  v a2s  . c  om*/
 * 
 * @param mapper
 *            der Dozer-Mapper
 * @param source
 *            das zu mappende Objekt
 * @param destinationType
 *            der Zieltyp
 * @return das gemappte Objekt
 */
@SuppressWarnings("unchecked")
public static Object map(Mapper mapper, Object source, Type destinationType) {
    if (source == null) {
        return null;
    }

    if (destinationType instanceof ParameterizedType) {
        ParameterizedType parDestinationType = (ParameterizedType) destinationType;

        Class<?> rawClass = (Class<?>) parDestinationType.getRawType();
        if (List.class.isAssignableFrom(rawClass)) {
            return mapCollection(mapper, source, parDestinationType, new ArrayList<Object>());
        } else if (SortedSet.class.isAssignableFrom(rawClass)) {
            return mapCollection(mapper, source, parDestinationType, new TreeSet<Object>());
        } else if (Set.class.isAssignableFrom(rawClass)) {
            return mapCollection(mapper, source, parDestinationType, new HashSet<Object>());
        } else if (SortedMap.class.isAssignableFrom(rawClass)) {
            return mapMap(mapper, source, parDestinationType, new TreeMap<Object, Object>());
        } else if (Map.class.isAssignableFrom(rawClass)) {
            return mapMap(mapper, source, parDestinationType, new HashMap<Object, Object>());
        }

        destinationType = parDestinationType.getRawType();
    }

    if (destinationType instanceof GenericArrayType) {
        if (!source.getClass().isArray()) {
            throw new IllegalArgumentException("Ein Mapping auf den Array-Typ " + destinationType
                    + " wird nicht untersttzt, wenn das Quellobjekt kein Array ist. Typ des Quellobjekts: "
                    + source.getClass());
        }

        // wir werden im Array Element pro Element mappen
        Type elementType = ((GenericArrayType) destinationType).getGenericComponentType();
        Object[] sourceArray = (Object[]) source;
        Object[] destinationArray = (Object[]) Array.newInstance((Class<?>) elementType, sourceArray.length);
        for (int i = 0; i < sourceArray.length; i++) {
            destinationArray[i] = MappingHelper.map(mapper, sourceArray[i], elementType);
        }
        return destinationArray;
    } else if ((destinationType instanceof Class<?>) && ((Class<?>) destinationType).isArray()) {
        if (!source.getClass().isArray()) {
            throw new IllegalArgumentException("Ein Mapping auf den Array-Typ " + destinationType
                    + " wird nicht untersttzt, wenn das Quellobjekt kein Array ist. Typ des Quellobjekts: "
                    + source.getClass());
        }
        Class<?> destinationTypeClass = (Class<?>) destinationType;
        // wir werden im Array Element pro Element mappen
        Type elementType = destinationTypeClass.getComponentType();
        Object[] sourceArray = (Object[]) source;
        Object[] destinationArray = (Object[]) Array.newInstance((Class<?>) elementType, sourceArray.length);
        for (int i = 0; i < sourceArray.length; i++) {
            destinationArray[i] = MappingHelper.map(mapper, sourceArray[i], elementType);
        }
        return destinationArray;
    }

    if (!(destinationType instanceof Class<?>)) {
        throw new IllegalArgumentException(
                "Ein Mapping auf Typ " + destinationType + " wird nicht untersttzt");
    }

    Class<?> destinationClass = (Class<?>) destinationType;

    if (ClassUtils.isPrimitiveOrWrapper(destinationClass) || MAPPING_BLACKLIST.contains(destinationClass)) {
        return source;
    } else if (destinationClass.isEnum()) {
        // wir mssen auf dieser Ebene Enums leider manuell mappen
        if (!(source instanceof Enum)) {
            throw new IllegalArgumentException("Ein Mapping auf ein Enum " + destinationClass
                    + " wird nicht untersttzt, da das Quellobjekt kein Enumobjekt ist (Quellobjektstyp: "
                    + source.getClass().toString() + ").");
        }
        return Enum.valueOf((Class<Enum>) destinationClass, ((Enum<?>) source).name());
    } else {
        return mapper.map(source, destinationClass);
    }
}

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/*from  w w  w  . j  a  va  2s. co  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:microsoft.exchange.webservices.data.misc.MapiTypeConverterMapEntry.java

/**
 * Gets the dim. If `array' is an array object returns its dimensions;
 * otherwise returns 0//from w  w  w  .j  a va2 s .  c  o  m
 *
 * @param array the array
 * @return the dim
 */
public static int getDim(Object array) {
    int dim = 0;
    Class<?> cls = array.getClass();
    while (cls.isArray()) {
        dim++;
        cls = cls.getComponentType();
    }
    return dim;
}

From source file:Main.java

public static <T> T[] convertToSingleArray(T[][] a_arrayOfArrays, Class<T[]> a_destType)
/*     */ {/*  ww w  .j  a  v a 2  s .  c om*/
    /* 230 */int iTotalLength = 0;
    /* 231 */for (Object[] srcArray : a_arrayOfArrays)
    /*     */ {
        /* 233 */if (srcArray == null)
            /*     */continue;
        /* 235 */iTotalLength += srcArray.length;
        /*     */}
    /*     */
    /* 242 */Object[] dest = (Object[]) (Object[]) Array.newInstance(a_destType.getComponentType(),
            iTotalLength);
    /*     */
    /* 245 */int iDestPointer = 0;
    /* 246 */for (Object[] srcArray : a_arrayOfArrays)
    /*     */ {
        /* 248 */if (srcArray == null)
            /*     */continue;
        /* 250 */System.arraycopy(srcArray, 0, dest, iDestPointer, srcArray.length);
        /* 251 */iDestPointer += srcArray.length;
        /*     */}
    /*     */
    /* 255 */return (T[]) dest;
    /*     */}

From source file:au.com.dw.testdatacapturej.reflection.util.ReflectionUtil.java

/**
 * Using reflection to get the class name will not work properly on arrays, it will return something like:
 *
 * Array of String's// www . j a v  a2 s  .c o  m
 * [Ljava.lang.String;
 *
 * Array of primitive int's
 * [I
 *
 * Array of Object's
 * [Ljava.lang.Object;
 *
 * Some we need to do some special handling to get it into the format we want for test data generation:
 *
 * java.lang.String[]
 * int[]
 * java.lang.Object[]
 *
 * @param array Should be an array
 * @return
 */
public static String getArrayClassName(Object array) {
    // sanity check that it is an array
    if (array.getClass().isArray()) {
        Class<?> clazz = array.getClass();
        Class<?> stringArrayComponentType = clazz.getComponentType();

        return stringArrayComponentType.getName() + FormatConstants.arraySuffix;
    } else {
        // shouldn't get here, but just return normal class name for non-arrays
        return array.getClass().getName();
    }
}

From source file:org.alfresco.module.org_alfresco_module_rm.api.PublicAPITestUtil.java

/**
 * Find all classes that are within the supplied type. For example a {@code Pair<Set<String>, Integer>} contains
 * references to four classes./*from ww w.  j  av a 2 s.  c o m*/
 *
 * @param type The type to examine.
 * @param processedTypes The set of types which have already been processed. If {@code type} is within this set then
 *            the method returns an empty set, to prevent analysis of the same type multiple times, and to guard
 *            against circular references. The underlying set is updated with the given type.
 * @return The set of classes used to form the given type.
 */
private static Set<Class<?>> getClassesFromType(Type type, Set<Type> processedTypes) {
    Set<Class<?>> returnClasses = new HashSet<>();

    if (processedTypes.add(type)) {
        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            returnClasses.add((Class<?>) parameterizedType.getRawType());

            for (Type t : parameterizedType.getActualTypeArguments()) {
                returnClasses.addAll(getClassesFromType(t, processedTypes));
            }
        } else if (type instanceof Class) {
            Class<?> clazz = (Class<?>) type;
            if (clazz.isArray()) {
                returnClasses.add(clazz.getComponentType());
            }
            returnClasses.add(clazz);
        } else if (type instanceof WildcardType) {
            // No-op - Caller can choose what type to use.
        } else if (type instanceof TypeVariable<?>) {
            TypeVariable<?> typeVariable = (TypeVariable<?>) type;
            for (Type bound : typeVariable.getBounds()) {
                returnClasses.addAll(getClassesFromType(bound, processedTypes));
            }
        } else if (type instanceof GenericArrayType) {
            GenericArrayType genericArrayType = (GenericArrayType) type;
            returnClasses
                    .addAll(getClassesFromType(genericArrayType.getGenericComponentType(), processedTypes));
        } else {
            throw new IllegalStateException("This test was not written to work with type " + type);
        }
    }
    return returnClasses;
}

From source file:gdt.data.entity.BaseHandler.java

private static String resolveName(String name, Class c) {
    if (name == null) {
        return name;
    }// w ww  .  j a  va 2  s. c  om
    if (!name.startsWith("/")) {
        while (c.isArray()) {
            c = c.getComponentType();
        }
        String baseName = c.getName();
        int index = baseName.lastIndexOf('.');
        if (index != -1) {
            name = baseName.substring(0, index).replace('.', '/') + "/" + name;
        }
    } else {
        name = name.substring(1);
    }
    return name;
}

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
 *///from  w w w. j  a  va 2s.  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);
    }
}