List of usage examples for java.lang.reflect Array newInstance
public static Object newInstance(Class<?> componentType, int... dimensions) throws IllegalArgumentException, NegativeArraySizeException
From source file:net.buffalo.protocal.util.ClassUtil.java
public static Object convertValue(Object value, Class targetType) { if (value.getClass().equals(targetType)) return value; if (targetType.isPrimitive()) { targetType = getWrapperClass(targetType); }/*from www . jav a2 s . c o m*/ if (targetType.isAssignableFrom(value.getClass())) return value; if ((value instanceof String || value instanceof Number) && Number.class.isAssignableFrom(targetType)) { try { Constructor ctor = targetType.getConstructor(new Class[] { String.class }); return ctor.newInstance(new Object[] { value.toString() }); } catch (Exception e) { LOGGER.error("convert type error", e); throw new RuntimeException( "Cannot convert from " + value.getClass().getName() + " to " + targetType, e); } } if (targetType.isArray() && Collection.class.isAssignableFrom(value.getClass())) { Collection collection = (Collection) value; Object array = Array.newInstance(targetType.getComponentType(), collection.size()); int i = 0; for (Iterator iter = collection.iterator(); iter.hasNext();) { Object val = iter.next(); Array.set(array, i++, val); } return array; } if (Collection.class.isAssignableFrom(targetType) && value.getClass().isArray()) { return Arrays.asList((Object[]) value); } throw new IllegalArgumentException( "Cannot convert from " + value.getClass().getName() + " to " + targetType); }
From source file:SoftSet.java
public Object[] toArray(Object[] a) { processQueue();/*from w ww . ja v a2 s . c o m*/ int size = map.size(); Object[] array = {}; if (a.length >= size) array = a; Iterator iter = map.values().iterator(); int index = 0; while (iter.hasNext()) { ComparableSoftReference csr = (ComparableSoftReference) iter.next(); Object value = csr.get(); // Create the correct array type if (array.length == 0) { if (value == null) { index++; continue; } Array.newInstance(value.getClass(), size); } array[index] = value; index++; } return array; }
From source file:Main.java
/** * Copies the specified range of the specified array into a new array. * The initial index of the range (<tt>from</tt>) must lie between zero * and <tt>original.length</tt>, inclusive. The value at * <tt>original[from]</tt> is placed into the initial element of the copy * (unless <tt>from == original.length</tt> or <tt>from == to</tt>). * Values from subsequent elements in the original array are placed into * subsequent elements in the copy. The final index of the range * (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>, * may be greater than <tt>original.length</tt>, in which case * <tt>null</tt> is placed in all elements of the copy whose index is * greater than or equal to <tt>original.length - from</tt>. The length * of the returned array will be <tt>to - from</tt>. * The resulting array is of the class <tt>newType</tt>. * * @param original the array from which a range is to be copied * @param from the initial index of the range to be copied, inclusive * @param to the final index of the range to be copied, exclusive. * (This index may lie outside the array.) * @param newType the class of the copy to be returned * @return a new array containing the specified range from the original array, * truncated or padded with nulls to obtain the required length * @throws ArrayIndexOutOfBoundsException if <tt>from < 0</tt> * or <tt>from > original.length()</tt> * @throws IllegalArgumentException if <tt>from > to</tt> * @throws NullPointerException if <tt>original</tt> is null * @throws ArrayStoreException if an element copied from * <tt>original</tt> is not of a runtime type that can be stored in * an array of class <tt>newType</tt>. * @since 1.6//ww w .j a v a 2s. com */ @SuppressWarnings("unchecked") public static <T, U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); 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:net.navasoft.madcoin.backend.services.rest.impl.BusinessService.java
/** * Gets the categories./*from w w w . j av a 2 s. co m*/ * * @return the categories * @since 21/08/2014, 11:56:35 PM */ @Override public SuccessResponseVO getCategories(String lob) { BusinessSuccessResponseVO response = new AppCategoriesSuccessResponseVO(); try { BusinessLines requested = dao.getByLogicalId(lob); response.setBusinessLines(requested); Collection<ServiceCategories> categories = requested.getServiceCategoriesCollection(); if (!categories.isEmpty()) { response.setCategories(requested.getServiceCategoriesCollection().toArray( (ServiceCategories[]) Array.newInstance(ServiceCategories.class, categories.size()))); return response; } else { throw ControllerExceptionFactory .createException(InsufficientCategoryException.class.getCanonicalName(), 1); } } catch (NoResultException e) { throw ControllerExceptionFactory.createException(InexistentLOBException.class.getCanonicalName(), 2, new ControllerExceptionArgument(lob)); } }
From source file:ar.com.zauber.commons.mom.MapObjectMapper.java
public <T> T[] toArray(final Class<T> clazz, final List<Map<String, Object>> list) { return (T[]) beanUtils.getConvertUtils().convert(list, Array.newInstance(clazz, 0).getClass()); }
From source file:br.msf.commons.util.ArrayUtils.java
@SuppressWarnings("SuspiciousSystemArraycopy") public static <T extends Object> T[] merge(final Class<T> itemClass, final boolean ignoreNulls, final Object... arrays) { if (getSize(arrays) == 0) { return null; }/* www. j av a2 s . co m*/ final T[] ret = (T[]) Array.newInstance(itemClass, getTotalSize(arrays)); int pos = 0; for (Object array : arrays) { final int len = getSize(array); if (len > 0) { if (ignoreNulls) { /* trata manualmente cada posio, ignorando os nulls */ for (int i = 0; i < len; i++) { T item = (T) Array.get(array, i); if (item != null) { ret[pos] = item; pos++; } } } else { /* faz a cpia nativa */ System.arraycopy(array, 0, ret, pos, len); pos += len; } } } return ret; }
From source file:com.adobe.acs.commons.mcp.util.AnnotatedFieldDeserializer.java
private static void parseInputList(Object target, String[] values, Field field) throws ReflectiveOperationException, ParseException { List convertedValues = new ArrayList(); Class type = getCollectionComponentType(field); for (String value : values) { Object val = convertValue(value, type); convertedValues.add(val); }//w ww . java 2 s. co m if (field.getType().isArray()) { Object array = Array.newInstance(field.getType().getComponentType(), convertedValues.size()); for (int i = 0; i < convertedValues.size(); i++) { Array.set(array, i, convertedValues.get(i)); } FieldUtils.writeField(field, target, array, true); } else { Collection c = (Collection) getInstantiatableListType(field.getType()).newInstance(); c.addAll(convertedValues); FieldUtils.writeField(field, target, c, true); } }
From source file:mitm.application.djigzo.james.MailAttributesUtils.java
/** * Returns the attribute value as an Array of clazz. Null if the attribute does not exist *//*from w w w . j a v a2 s. co m*/ @SuppressWarnings("unchecked") public static <T> T[] getAttributeAsArray(Mail mail, String attribute, Class<?> clazz) { T[] result = null; List<T> list = getAttributeAsList(mail, attribute, clazz); if (list != null) { result = (T[]) Array.newInstance(clazz, list.size()); /* * Note: we assume that the list returned from getAttributeAsList is an ArrayList */ result = ((ArrayList<T>) list).toArray(result); } return result; }
From source file:ClassUtils.java
/** * Replacement for <code>Class.forName()</code> that also returns Class instances * for primitives (like "int") and array class names (like "String[]"). * @param name the name of the Class//from w w w .j a v a 2s . c om * @param classLoader the class loader to use * (may be <code>null</code>, which indicates the default class loader) * @return Class instance for the supplied name * @throws ClassNotFoundException if the class was not found * @throws LinkageError if the class file could not be loaded * @see Class#forName(String, boolean, ClassLoader) */ public static Class forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError { Class clazz = resolvePrimitiveClassName(name); if (clazz != null) { return clazz; } // "java.lang.String[]" style arrays if (name.endsWith(ARRAY_SUFFIX)) { String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length()); Class elementClass = forName(elementClassName, classLoader); return Array.newInstance(elementClass, 0).getClass(); } // "[Ljava.lang.String;" style arrays int internalArrayMarker = name.indexOf(INTERNAL_ARRAY_PREFIX); if (internalArrayMarker != -1 && name.endsWith(";")) { String elementClassName = null; if (internalArrayMarker == 0) { elementClassName = name.substring(INTERNAL_ARRAY_PREFIX.length(), name.length() - 1); } else if (name.startsWith("[")) { elementClassName = name.substring(1); } Class elementClass = forName(elementClassName, classLoader); return Array.newInstance(elementClass, 0).getClass(); } ClassLoader classLoaderToUse = classLoader; if (classLoaderToUse == null) { classLoaderToUse = getDefaultClassLoader(); } return classLoaderToUse.loadClass(name); }
From source file:com.swingtech.commons.testing.JavaBeanTester.java
private static Object buildValue(Class<?> clazz) throws InstantiationException, IllegalAccessException, IllegalArgumentException, SecurityException, InvocationTargetException { // If we are using a Mocking framework try that first... final Object mockedObject = buildMockValue(clazz); if (mockedObject != null) { return mockedObject; }//from w w w . ja va 2 s . c om // Next check for a no-arg constructor final Constructor<?>[] ctrs = clazz.getConstructors(); for (Constructor<?> ctr : ctrs) { if (ctr.getParameterTypes().length == 0) { // The class has a no-arg constructor, so just call it return ctr.newInstance(); } } // Specific rules for common classes if (clazz == String.class) { return "testvalue"; } else if (clazz.isArray()) { return Array.newInstance(clazz.getComponentType(), 1); } else if (clazz == boolean.class || clazz == Boolean.class) { return true; } else if (clazz == int.class || clazz == Integer.class) { return 1; } else if (clazz == long.class || clazz == Long.class) { return 1L; } else if (clazz == double.class || clazz == Double.class) { return 1.0D; } else if (clazz == float.class || clazz == Float.class) { return 1.0F; } else if (clazz == char.class || clazz == Character.class) { return 'Y'; // Add your own rules here } else { fail("Unable to build an instance of class " + clazz.getName() + ", please add some code to the " + JavaBeanTester.class.getName() + " class to do this."); return null; // for the compiler } }