List of usage examples for java.lang.reflect Array newInstance
public static Object newInstance(Class<?> componentType, int... dimensions) throws IllegalArgumentException, NegativeArraySizeException
From source file:com.adobe.acs.commons.util.impl.ValueMapTypeConverter.java
private Object handleArrayProperty(Class<?> clazz) { // handle case of primitive/wrapper arrays Class<?> componentType = clazz.getComponentType(); if (componentType.isPrimitive()) { Class<?> wrapper = ClassUtils.primitiveToWrapper(componentType); if (wrapper != componentType) { Object wrapperArray = getValueFromMap(Array.newInstance(wrapper, 0).getClass()); if (wrapperArray != null) { return unwrapArray(wrapperArray, componentType); }//from w w w .j ava 2s.c om } } else { Object wrapperArray = getValueFromMap(Array.newInstance(componentType, 0).getClass()); if (wrapperArray != null) { return unwrapArray(wrapperArray, componentType); } } return null; }
From source file:org.mstc.zmq.json.Decoder.java
@SuppressWarnings("unchecked") public static void decode(String input, Field[] fields, Object b) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS); if (logger.isDebugEnabled()) logger.debug(input);/*from w w w . java 2 s. c om*/ JsonFactory factory = mapper.getFactory(); try (JsonParser jp = factory.createParser(input)) { /* Sanity check: verify that we got "Json Object" */ if (jp.nextToken() != JsonToken.START_OBJECT) { throw new IOException("Expected data to start with an Object"); } /* Iterate over object fields */ while (jp.nextToken() != JsonToken.END_OBJECT) { String fieldName = jp.getCurrentName(); jp.nextToken(); Field field = getField(fieldName, fields); if (field == null) { throw new IOException( "Could not find field [" + fieldName + "] on class " + b.getClass().getName()); } try { if (field.getType().isAssignableFrom(List.class)) { String adder = getAdder(fieldName); TypeFactory t = TypeFactory.defaultInstance(); ParameterizedType listType = (ParameterizedType) field.getGenericType(); Class<?> listClass = (Class<?>) listType.getActualTypeArguments()[0]; List list = mapper.readValue(jp.getValueAsString(), t.constructCollectionType(List.class, listClass)); Method m = b.getClass().getDeclaredMethod(adder, Collection.class); m.invoke(b, list); } else if (field.getType().isArray()) { Class<?> type = field.getType(); String setter = getSetter(fieldName); Method m = b.getClass().getDeclaredMethod(setter, field.getType()); logger.info("Field {} is array of {}[], {}, using method {}", field.getName(), field.getType().getComponentType(), jp.getCurrentToken().name(), m); if (jp.getCurrentToken().id() == JsonToken.START_ARRAY.id()) { List list = new ArrayList(); while (jp.nextToken() != JsonToken.END_ARRAY) { String value = jp.getText(); switch (jp.getCurrentToken()) { case VALUE_STRING: list.add(value); break; case VALUE_NUMBER_INT: if (type.getComponentType().isAssignableFrom(double.class)) { list.add(Double.parseDouble(value)); } else if (type.getComponentType().isAssignableFrom(float.class)) { list.add(Float.parseFloat(value)); } else { list.add(Integer.parseInt(value)); } break; case VALUE_NUMBER_FLOAT: logger.info("Add float"); list.add(jp.getFloatValue()); break; case VALUE_NULL: break; default: logger.warn("[3] Not sure how to handle {} yet", jp.getCurrentToken().name()); } } Object array = Array.newInstance(field.getType().getComponentType(), list.size()); for (int i = 0; i < list.size(); i++) { Object val = list.get(i); Array.set(array, i, val); } m.invoke(b, array); } else { if (type.getComponentType().isAssignableFrom(byte.class)) { m.invoke(b, jp.getBinaryValue()); } } } else { String setter = getSetter(fieldName); logger.debug("{}: {}", setter, field.getType().getName()); Method m = b.getClass().getDeclaredMethod(setter, field.getType()); switch (jp.getCurrentToken()) { case VALUE_STRING: m.invoke(b, jp.getText()); break; case VALUE_NUMBER_INT: m.invoke(b, jp.getIntValue()); break; case VALUE_NUMBER_FLOAT: m.invoke(b, jp.getFloatValue()); break; case VALUE_NULL: logger.debug("Skip invoking {}.{}, property is null", b.getClass().getName(), m.getName()); break; case START_OBJECT: StringBuilder sb = new StringBuilder(); while (jp.nextToken() != JsonToken.END_OBJECT) { switch (jp.getCurrentToken()) { case VALUE_STRING: sb.append("\"").append(jp.getText()).append("\""); break; case FIELD_NAME: if (sb.length() > 0) sb.append(","); sb.append("\"").append(jp.getText()).append("\"").append(":"); break; case VALUE_NUMBER_INT: sb.append(jp.getIntValue()); break; case VALUE_NUMBER_FLOAT: sb.append(jp.getFloatValue()); break; case VALUE_NULL: sb.append("null"); break; default: logger.warn("[2] Not sure how to handle {} yet", jp.getCurrentToken().name()); } } String s = String.format("%s%s%s", JsonToken.START_OBJECT.asString(), sb.toString(), JsonToken.END_OBJECT.asString()); Object parsed = getNested(field.getType(), s.getBytes()); m.invoke(b, parsed); break; default: logger.warn("[1] Not sure how to handle {} yet", jp.getCurrentToken().name()); } } } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException e) { logger.error("Failed setting field [{}], builder: {}", fieldName, b.getClass().getName(), e); } } } }
From source file:h2o.common.spring.util.ObjectUtils.java
/** * Append the given Object to the given array, returning a new array * consisting of the input array contents plus the given Object. * @param array the array to append to (can be <code>null</code>) * @param obj the Object to append//ww w . ja va2 s . c o m * @return the new array (of the same component type; never <code>null</code>) */ @SuppressWarnings("rawtypes") public static Object[] addObjectToArray(Object[] array, Object obj) { Class compType = Object.class; if (array != null) { compType = array.getClass().getComponentType(); } else if (obj != null) { compType = obj.getClass(); } int newArrLength = (array != null ? array.length + 1 : 1); Object[] newArr = (Object[]) Array.newInstance(compType, newArrLength); if (array != null) { System.arraycopy(array, 0, newArr, 0, array.length); } newArr[newArr.length - 1] = obj; return newArr; }
From source file:com.opengamma.analytics.math.curve.ObjectsCurve.java
/** * /*ww w. ja va2 s . co m*/ * @param xData A list of <i>x</i> data points, assumed to be sorted ascending, not null * @param yData A list of <i>y</i> data points, not null, contains same number of entries as <i>x</i> * @param isSorted Is the <i>x</i>-data sorted */ public ObjectsCurve(final List<T> xData, final List<U> yData, final boolean isSorted) { super(); ArgumentChecker.notNull(xData, "x data"); ArgumentChecker.notNull(yData, "y data"); _n = xData.size(); ArgumentChecker.isTrue(_n == yData.size(), "size of x data {} does not match size of y data {}", _n, yData.size()); _xData = xData.toArray((T[]) Array.newInstance(xData.get(0).getClass(), 0)); _yData = yData.toArray((U[]) Array.newInstance(yData.get(0).getClass(), 0)); if (!isSorted) { ParallelArrayBinarySort.parallelBinarySort(_xData, _yData); } }
From source file:io.konik.utils.RandomInvoiceGenerator.java
private Object createNewInstance(Class<?> root) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { try {/*from w ww . ja va 2 s. c om*/ if (root.isArray()) { Object[] array = (Object[]) Array.newInstance(root.getComponentType(), 1); Class<?> componentType = root.getComponentType(); array[0] = populteData(componentType, componentType.getName()); return array; } return root.newInstance(); } catch (IllegalAccessException e) { Constructor<?> biggestConstructor = findBiggestConstructor(root); //for each parameter populate data Class<?>[] constructorParameters = biggestConstructor.getParameterTypes(); Object[] constructorParameterObjects = new Object[constructorParameters.length]; for (int i = 0; i < constructorParameters.length; i++) { Class<?> cp = constructorParameters[i]; constructorParameterObjects[i] = populteData(cp, biggestConstructor.getName()); } return biggestConstructor.newInstance(constructorParameterObjects); } catch (InstantiationException e) { if (root.equals(CommonTax.class)) { // return ZfDateFactory.create(supportedDateFormatts[random.nextInt(3)]); } // throw e; e.printStackTrace(); return null; } }
From source file:com.opengamma.language.definition.JavaTypeInfo.java
@SuppressWarnings("unchecked") public JavaTypeInfo<?> arrayOfWithAllowNull(final boolean allowNull) { return new JavaTypeInfo<Object>((Class<Object>) Array.newInstance(_rawClass, 0).getClass(), allowNull, false, null, new JavaTypeInfo<?>[] { this }); }
From source file:Main.java
/** * <p>Removes the element at the specified position from the specified array. * All subsequent elements are shifted to the left (substracts one from * their indices).</p>/* ww w. j a v a 2 s. co m*/ * * <p>This method returns a new array with the same elements of the input * array except the element on the specified position. The component * type of the returned array is always the same as that of the input * array.</p> * * <p>If the input array is <code>null</code>, an IndexOutOfBoundsException * will be thrown, because in that case no valid index can be specified.</p> * * @param array the array to remove the element from, may not be <code>null</code> * @param index the position of the element to be removed * @return A new array containing the existing elements except the element * at the specified position. * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index >= array.length), or if the array is <code>null</code>. * @since 2.1 */ private static Object remove(Object array, int index) { int length = getLength(array); if (index < 0 || index >= length) { throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length); } Object result = Array.newInstance(array.getClass().getComponentType(), length - 1); System.arraycopy(array, 0, result, 0, index); if (index < length - 1) { System.arraycopy(array, index + 1, result, index, length - index - 1); } return result; }
From source file:jef.tools.ArrayUtils.java
/** * null/*from w w w . jav a2 s . co m*/ * * @param <T> * @param arr1 * @return */ @SuppressWarnings("unchecked") public static <T> T[] removeNull(T[] arr1) { List<T> list = new ArrayList<T>(arr1.length); for (T e : arr1) { if (e != null) { list.add(e); } } if (list.size() == arr1.length) return arr1; // ? list.toArray(arr1); // ArrayList.toArray[]List?Listnull. // ?null T[] t = (T[]) Array.newInstance(arr1.getClass().getComponentType(), list.size()); return list.toArray(t); }
From source file:com.dsj.core.beans.ObjectUtils.java
/** * Convert a primitive array to an object array of primitive wrapper * objects./*from w w w . j av a2 s .c o m*/ * * @param primitiveArray * the primitive array * @return the object array * @throws IllegalArgumentException * if the parameter is not a primitive array */ public static Object[] toObjectArray(Object primitiveArray) { if (primitiveArray == null) { return new Object[0]; } Class clazz = primitiveArray.getClass(); if (!clazz.isArray() || !clazz.getComponentType().isPrimitive()) { throw new IllegalArgumentException("The specified parameter is not a primitive array"); } int length = Array.getLength(primitiveArray); if (length == 0) { return new Object[0]; } Class wrapperType = Array.get(primitiveArray, 0).getClass(); Object[] newArray = (Object[]) Array.newInstance(wrapperType, length); for (int i = 0; i < length; i++) { newArray[i] = Array.get(primitiveArray, i); } return newArray; }
From source file:edu.stevens.cpe.reservior.Reservoir.java
/** * Initialize all the neuron//from www . j a v a2s .co m * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException * @throws InstantiationException * @throws SecurityException * @throws IllegalArgumentException */ private void createNeurons() throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { neurons = (T[]) Array.newInstance(neuronClass, neuronCount); for (int i = 0; i < neuronCount; i++) { neurons[i] = neuronClass.getConstructor(Integer.class).newInstance(i); } }