Java Code Examples for java.lang.reflect.Array#newInstance()
The following examples show how to use
java.lang.reflect.Array#newInstance() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ObjectUtils.java From dolphin with Apache License 2.0 | 6 votes |
/** * Convert the given array (which may be a primitive array) to an * object array (if necessary of primitive wrapper objects). * <p>A {@code null} source value will be converted to an * empty Object array. * @param source the (potentially primitive) array * @return the corresponding object array (never {@code null}) * @throws IllegalArgumentException if the parameter is not an array */ public static Object[] toObjectArray(Object source) { if (source instanceof Object[]) { return (Object[]) source; } if (source == null) { return new Object[0]; } if (!source.getClass().isArray()) { throw new IllegalArgumentException("Source is not an array: " + source); } int length = Array.getLength(source); if (length == 0) { return new Object[0]; } Class<?> wrapperType = Array.get(source, 0).getClass(); Object[] newArray = (Object[]) Array.newInstance(wrapperType, length); for (int i = 0; i < length; i++) { newArray[i] = Array.get(source, i); } return newArray; }
Example 2
Source File: Hibernate1.java From ysoserial-modified with MIT License | 6 votes |
public static Object makeHibernate4Getter ( Class<?> tplClass, String method ) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class<?> getterIf = Class.forName("org.hibernate.property.Getter"); Class<?> basicGetter = Class.forName("org.hibernate.property.BasicPropertyAccessor$BasicGetter"); Constructor<?> bgCon = basicGetter.getDeclaredConstructor(Class.class, Method.class, String.class); bgCon.setAccessible(true); if ( !method.startsWith("get") ) { throw new IllegalArgumentException("Hibernate4 can only call getters"); } String propName = Character.toLowerCase(method.charAt(3)) + method.substring(4); Object g = bgCon.newInstance(tplClass, tplClass.getDeclaredMethod(method), propName); Object arr = Array.newInstance(getterIf, 1); Array.set(arr, 0, g); return arr; }
Example 3
Source File: ReflectAccelerator.java From Small with Apache License 2.0 | 6 votes |
private static void sliceArray(Object target, Field arrField, int deleteIndex) throws IllegalAccessException { Object[] original = (Object[]) arrField.get(target); if (original.length == 0) return; Object[] sliced = (Object[]) Array.newInstance( original.getClass().getComponentType(), original.length - 1); if (deleteIndex > 0) { // Copy left elements System.arraycopy(original, 0, sliced, 0, deleteIndex); } int rightCount = original.length - deleteIndex - 1; if (rightCount > 0) { // Copy right elements System.arraycopy(original, deleteIndex + 1, sliced, deleteIndex, rightCount); } arrField.set(target, sliced); }
Example 4
Source File: CuckooHashTable.java From algorithms-sedgewick-wayne with MIT License | 6 votes |
CuckooHashTable(int size) { this.size = size; keysAndValues = (Entry[][]) Array.newInstance(Entry.class, 2, size); //The lg of the hash table size //Used to distribute keys uniformly in the hash function int lgM = (int) (Math.log(size) / Math.log(2)); hashFunctions = new HashFunction[2]; for(int i = 0; i < 2; i++) { int randomCoefficientA = StdRandom.uniform(Integer.MAX_VALUE); int randomCoefficientB = StdRandom.uniform(Integer.MAX_VALUE); hashFunctions[i] = new HashFunction(randomCoefficientA, randomCoefficientB, lgM); } }
Example 5
Source File: Utils.java From obfuscator with MIT License | 5 votes |
public static <T> T[] concatenate(T[] a, T[] b) { int aLen = a.length; int bLen = b.length; @SuppressWarnings("unchecked") T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen); System.arraycopy(a, 0, c, 0, aLen); System.arraycopy(b, 0, c, aLen, bLen); return c; }
Example 6
Source File: Lang_35_ArrayUtils_s.java From coming with MIT License | 5 votes |
/** * <p>Adds all the elements of the given arrays into a new array.</p> * <p>The new array contains all of the element of <code>array1</code> followed * by all of the elements <code>array2</code>. When an array is returned, it is always * a new array.</p> * * <pre> * ArrayUtils.addAll(null, null) = null * ArrayUtils.addAll(array1, null) = cloned copy of array1 * ArrayUtils.addAll(null, array2) = cloned copy of array2 * ArrayUtils.addAll([], []) = [] * ArrayUtils.addAll([null], [null]) = [null, null] * ArrayUtils.addAll(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"] * </pre> * * @param array1 the first array whose elements are added to the new array, may be <code>null</code> * @param array2 the second array whose elements are added to the new array, may be <code>null</code> * @return The new array, <code>null</code> if both arrays are <code>null</code>. * The type of the new array is the type of the first array, * unless the first array is null, in which case the type is the same as the second array. * @since 2.1 * @throws IllegalArgumentException if the array types are incompatible */ public static <T> T[] addAll(T[] array1, T... array2) { if (array1 == null) { return clone(array2); } else if (array2 == null) { return clone(array1); } final Class<?> type1 = array1.getClass().getComponentType(); @SuppressWarnings("unchecked") // OK, because array is of type T T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length); System.arraycopy(array1, 0, joinedArray, 0, array1.length); try { System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); } catch (ArrayStoreException ase) { // Check if problem was due to incompatible types /* * We do this here, rather than before the copy because: * - it would be a wasted check most of the time * - safer, in case check turns out to be too strict */ final Class<?> type2 = array2.getClass().getComponentType(); if (!type1.isAssignableFrom(type2)){ throw new IllegalArgumentException("Cannot store "+type2.getName()+" in an array of "+type1.getName(), ase); } throw ase; // No, so rethrow original } return joinedArray; }
Example 7
Source File: CollectionUtils.java From OpenModsLib with MIT License | 5 votes |
private static <A, B> Object allocateArray(Function<A, B> transformer, final int length) { final Class<?> transformerCls = transformer.getClass(); Class<?> componentType = findTypeFromGenericInterface(transformerCls); if (componentType == null) componentType = findTypeFromMethod(transformerCls); Preconditions.checkState(componentType != null, "Failed to find type for class %s", transformer); return Array.newInstance(componentType, length); }
Example 8
Source File: ArrayUtil.java From javaide with GNU General Public License v3.0 | 5 votes |
public static <T> T[] toArray(List<T> list, Class<T> clazz) { @SuppressWarnings("unchecked") T[] result = (T[]) Array.newInstance(clazz, list.size()); for (int i = 0; i < list.size(); i++) { result[i] = list.get(i); } return result; }
Example 9
Source File: LeafNode.java From a-foundation with Apache License 2.0 | 5 votes |
@SuppressWarnings ("unchecked") private <T> T[] splitAndAddLeft (Class<T> componentType, T[] orig, int newIdx, T newEl) { final int idxMedian = orig.length / 2; if (newIdx > idxMedian) { return Arrays.copyOf (orig, idxMedian); } final T[] result = (T[]) Array.newInstance (componentType, idxMedian + 1); System.arraycopy (orig, 0, result, 0, newIdx); result[newIdx] = newEl; System.arraycopy (orig, newIdx, result, newIdx + 1, idxMedian - newIdx); return result; }
Example 10
Source File: LinearSelector.java From cs-review with MIT License | 5 votes |
@SuppressWarnings("unchecked") public int select(E[] items, int[] positions, int from, int to, int order) { if (to - from <= 5) { sort(items, positions, from, to); return order; } int groups = (int) Math.ceil((to - from) / 5.0); final E[] medians = (E[]) Array.newInstance(items.getClass().getComponentType(), groups); final int[] medianPositions = new int[groups]; //sort each group of five, so that their median is immediately reachable for (int i = 0; i < groups; i ++) { final int lowerBound = from + 5 * i; final int upperBound = Math.min(to, from + 5 + 5 * i); sort(items, positions, lowerBound, upperBound); int median = averagePosition(lowerBound, upperBound); medianPositions[i] = median; medians[i] = items[median]; } final int medianOfMedians = medianPositions[select(medians, medianPositions, 0, medians.length, averagePosition(0, medians.length))]; final int pivot = partition(items, from, to, medianOfMedians); if (pivot == order) { return pivot; } else if (order < pivot) { return select(items, positions, from, pivot-1, order); } else { return select(items, positions, pivot+1, to, order); } }
Example 11
Source File: MultiDex.java From atlas with Apache License 2.0 | 5 votes |
/** * Replace the value of a field containing a non null array, by a new array containing the * elements of the original array plus the elements of extraElements. * * @param instance the instance whose field is to be modified. * @param fieldName the field to modify. * @param extraElements elements to append at the end of the array. */ private static void expandFieldArray(Object instance, String fieldName, Object[] extraElements) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field jlrField = findField(instance, fieldName); Object[] original = (Object[]) jlrField.get(instance); Object[] combined = (Object[]) Array.newInstance( original.getClass().getComponentType(), original.length + extraElements.length); System.arraycopy(original, 0, combined, 0, original.length); System.arraycopy(extraElements, 0, combined, original.length, extraElements.length); jlrField.set(instance, combined); }
Example 12
Source File: DRDAStatement.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
private static Object growArray(Object array) { final int oldLen = Array.getLength(array); Object tmp = Array.newInstance(array.getClass().getComponentType(), Math.max(oldLen,1)*2); System.arraycopy(array, 0, tmp, 0, oldLen); return tmp; }
Example 13
Source File: MessageFormatterTest.java From openpojo with Apache License 2.0 | 5 votes |
@Test public final void testActualArraySentAsObjectWithNulls() { final String expected = "[3, null, 14]"; final Object array = Array.newInstance(Integer.class, 3); Array.set(array, 0, 3); Array.set(array, 2, 14); Assert.assertEquals(expected, MessageFormatter.format(array)); }
Example 14
Source File: ClientUtils.java From ignite with Apache License 2.0 | 5 votes |
/** * Unwrap array with binary objects. */ private Object[] unwrapArray(Object[] arr, BinaryReaderHandles hnds) { if (BinaryUtils.knownArray(arr)) return arr; Object[] res = (Object[])Array.newInstance(arr.getClass().getComponentType(), arr.length); for (int i = 0; i < arr.length; i++) res[i] = unwrapBinary(arr[i], hnds); return res; }
Example 15
Source File: StripedLockHolder.java From consulo with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") protected StripedLockHolder(@Nonnull Class<T> aClass) { ourLocks = (T[])Array.newInstance(aClass, NUM_LOCKS); for (int i = 0; i < ourLocks.length; i++) { ourLocks[i] = create(); } }
Example 16
Source File: ArrayUtils.java From btree4j with Apache License 2.0 | 4 votes |
public static Object resize(final Object[] ary, final int length) { final Object newary = Array.newInstance(ary.getClass().getComponentType(), length); final int copysize = length > ary.length ? length : ary.length; System.arraycopy(ary, 0, newary, 0, copysize); return newary; }
Example 17
Source File: ObjectProcessor.java From sofa-acts with Apache License 2.0 | 4 votes |
/** * * @param property * @param argumentClass * @param fieldClass * @param fieldName * @param referedValue * @return */ protected Object generateComplexCollection(BaseUnitProperty property, Class<?> argumentClass, Class<?> fieldClass, String fieldName, Object referedValue) { Object fieldValue = null; if (property.getExpectValue() == null) { return null; } if (property instanceof ListObjectUnitProperty) { ListObjectUnitProperty listProperty = (ListObjectUnitProperty) property; listProperty.setTargetCSVPath(FileUtil.getRelativePath(argumentClass.getSimpleName() + ".csv", this.csvPath)); listProperty.setClassType(argumentClass); return listProperty.genObject(classLoader); } else if (property instanceof MapObjectUnitProperty) { MapObjectUnitProperty mapProperty = (MapObjectUnitProperty) property; if (String.valueOf(mapProperty.getBaseValue()).contains(".csv@")) { mapProperty.setTargetCSVPath(FileUtil.getRelativePath(argumentClass.getSimpleName() + ".csv", this.csvPath)); } mapProperty.setClassType(argumentClass); return mapProperty.genObject(classLoader); } else if (!(property.getExpectValue() instanceof String)) { ActsLogUtil.fail(logger, "in yaml, the type of element of collection must be string"); } String value = String.valueOf(referedValue); if (StringUtils.isBlank(value)) { return null; } else if (StringUtils.equals("@element_empty@", value)) { return objectTypeManager.getCollectionObject(fieldClass); } else { String[] valueParts = value.split("@"); Assert .assertTrue("desc of complex obj must contain only one @", valueParts.length == 2); String[] values = valueParts[1].trim().split(";"); if (fieldClass.isArray()) { fieldValue = Array.newInstance(fieldClass.getComponentType(), valueParts.length); } else { fieldValue = objectTypeManager.getCollectionObject(fieldClass); } for (int i = 0; i < values.length; i++) { Object valuePart = generateChildObject(property, argumentClass, fieldName, valueParts[0].trim() + "@" + values[i].trim()); objectTypeManager.setCollectionObjectValue(fieldValue, valuePart, values[i], i, fieldClass); } } return fieldValue; }
Example 18
Source File: MultiColumnListAdapter.java From multi-column-list-adapter with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") private V[] newGridItemViewHolderArray(int numColumns) { Class<V> gridItemViewHolderClass = getGridItemViewHolderClass(); return (V[]) Array.newInstance(gridItemViewHolderClass, numColumns); }
Example 19
Source File: NoTypeArrayData.java From openjdk-8-source with GNU General Public License v2.0 | 4 votes |
@Override public Object asArrayOfType(final Class<?> componentType) { return Array.newInstance(componentType, 0); }
Example 20
Source File: AWTEventMulticaster.java From TencentKona-8 with GNU General Public License v2.0 | 3 votes |
/** * Returns an array of all the objects chained as * <code><em>Foo</em>Listener</code>s by the specified * <code>java.util.EventListener</code>. * <code><em>Foo</em>Listener</code>s are chained by the * <code>AWTEventMulticaster</code> using the * <code>add<em>Foo</em>Listener</code> method. * If a <code>null</code> listener is specified, this method returns an * empty array. If the specified listener is not an instance of * <code>AWTEventMulticaster</code>, this method returns an array which * contains only the specified listener. If no such listeners are chained, * this method returns an empty array. * * @param l the specified <code>java.util.EventListener</code> * @param listenerType the type of listeners requested; this parameter * should specify an interface that descends from * <code>java.util.EventListener</code> * @return an array of all objects chained as * <code><em>Foo</em>Listener</code>s by the specified multicast * listener, or an empty array if no such listeners have been * chained by the specified multicast listener * @exception NullPointerException if the specified * {@code listenertype} parameter is {@code null} * @exception ClassCastException if <code>listenerType</code> * doesn't specify a class or interface that implements * <code>java.util.EventListener</code> * * @since 1.4 */ @SuppressWarnings("unchecked") public static <T extends EventListener> T[] getListeners(EventListener l, Class<T> listenerType) { if (listenerType == null) { throw new NullPointerException ("Listener type should not be null"); } int n = getListenerCount(l, listenerType); T[] result = (T[])Array.newInstance(listenerType, n); populateListenerArray(result, l, 0); return result; }