Java Code Examples for java.lang.reflect.Array.newInstance()

The following are Jave code examples for showing how to use newInstance() of the java.lang.reflect.Array class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: jetedge   File: ArrayLimiter.java   View Source Code Vote up 6 votes
@Override
public Supplier<Object[]> generateSupplier(Random random) {
    if (this.limiter == null) {
        throw new LimiterConstructionException("Error creating ArrayLimiter : Missing internal Limiter");
    }
    return () -> {
        try {
            int count = range == 0 ? offset : random.nextInt(range) + offset;
            Object[] objectArray = (Object[]) Array.newInstance(limiter.generateSupplier(random).get().getClass(), count);
            for (int i = 0; i < count; i++) {
                objectArray[i] = limiter.generateSupplier(random).get();
            }
            return objectArray;
        } catch (Exception e) {
            throw new PojoConstructionException("Failed to create object for ArrayLimiter: ", e);
        }
    };
}
 
Example 2
Project: HCFCore   File: CompositeCollection.java   View Source Code Vote up 6 votes
/**
 * Returns an object array, populating the supplied array if possible.
 * See <code>Collection</code> interface for full details.
 *
 * @param <T>  the type of the elements in the collection
 * @param array  the array to use, populating if possible
 * @return an array of all the elements in the collection
 */
@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(final T[] array) {
    final int size = size();
    Object[] result = null;
    if (array.length >= size) {
        result = array;
    } else {
        result = (Object[]) Array.newInstance(array.getClass().getComponentType(), size);
    }

    int offset = 0;
    for (final Collection<E> item : all) {
        for (final E e : item) {
            result[offset++] = e;
        }
    }
    if (result.length > size) {
        result[size] = null;
    }
    return (T[]) result;
}
 
Example 3
Project: funcj   File: FunctorsGenEx.java   View Source Code Vote up 6 votes
/**
 * Map a function over an array.
 * @param f         the function to apply to each element of the array
 * @param from      the input array
 * @param to        the output array
 * @param <A>       the element type of the input array
 * @param <B>       the element type of the output array
 * @param <X>       the exception type
 * @return          the output array
 * @throws X        the exception thrown by the function
 */
@SuppressWarnings("unchecked")
public static <A, B, X extends Exception> B[] map(F<A, B, X> f, A[] from, B[] to) throws X {
    final int l = from.length;
    if (to.length != l) {
        final Class<?> type = to.getClass();
        to = (type == Object[].class)
                ? (B[]) new Object[l]
                : (B[]) Array.newInstance(type.getComponentType(), l);
    }

    for (int i = 0; i < from.length; ++i) {
        to[i] = f.apply(from[i]);
    }

    return to;
}
 
Example 4
Project: directory-mavibot   File: InMemoryBTreeTest.java   View Source Code Vote up 6 votes
private Page<Integer, String> createLeaf( BTree<Integer, String> btree, long revision,
    Tuple<Integer, String>... tuples )
{
    InMemoryLeaf<Integer, String> leaf = new InMemoryLeaf<Integer, String>( btree );
    int pos = 0;
    leaf.setRevision( revision );
    leaf.setNbElems( tuples.length );
    leaf.setKeys( new KeyHolder[leaf.getNbElems()] );
    leaf.values = ( InMemoryValueHolder<String>[] ) Array
        .newInstance( InMemoryValueHolder.class, leaf.getNbElems() );

    for ( Tuple<Integer, String> tuple : tuples )
    {
        leaf.setKey( pos, new KeyHolder<Integer>( tuple.getKey() ) );
        leaf.values[pos] = new InMemoryValueHolder<String>( btree, tuple.getValue() );
        pos++;
    }

    return leaf;
}
 
Example 5
Project: PlusGram   File: AnimatorSetProxy.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
public static <T, U> T[] copyOfRange(U[] original, int start, int end, Class<? extends T[]> newType) {
    if (start > end) {
        throw new IllegalArgumentException();
    }
    int originalLength = original.length;
    if (start < 0 || start > originalLength) {
        throw new ArrayIndexOutOfBoundsException();
    }
    int resultLength = end - start;
    int copyLength = Math.min(resultLength, originalLength - start);
    T[] result = (T[]) Array.newInstance(newType.getComponentType(), resultLength);
    System.arraycopy(original, start, result, 0, copyLength);
    return result;
}
 
Example 6
Project: RxJava3-preview   File: ReplaySubject.java   View Source Code Vote up 5 votes
@Override
@SuppressWarnings("unchecked")
public T[] getValues(T[] array) {
    int s = size;
    if (s == 0) {
        if (array.length != 0) {
            array[0] = null;
        }
        return array;
    }
    List<Object> b = buffer;
    Object o = b.get(s - 1);

    if (NotificationLite.isComplete(o) || NotificationLite.isError(o)) {
        s--;
        if (s == 0) {
            if (array.length != 0) {
                array[0] = null;
            }
            return array;
        }
    }


    if (array.length < s) {
        array = (T[])Array.newInstance(array.getClass().getComponentType(), s);
    }
    for (int i = 0; i < s; i++) {
        array[i] = (T)b.get(i);
    }
    if (array.length > s) {
        array[s] = null;
    }

    return array;
}
 
Example 7
Project: openjdk-jdk10   File: StringListImpl.java   View Source Code Vote up 5 votes
public Object[] toArray(Object[] a) {
    if (fVector != null) {
        return fVector.toArray(a);
    }
    if (a.length < fLength) {
        Class arrayClass = a.getClass();
        Class componentType = arrayClass.getComponentType();
        a = (Object[]) Array.newInstance(componentType, fLength);
    }
    toArray0(a);
    if (a.length > fLength) {
        a[fLength] = null;
    }
    return a;
}
 
Example 8
Project: directory-mavibot   File: AbstractPage.java   View Source Code Vote up 5 votes
/**
 * Internal constructor used to create Page instance used when a page is being copied or overflow
 */
@SuppressWarnings("unchecked")
// Cannot create an array of generic objects
protected AbstractPage( BTree<K, V> btree, long revision, int nbElems )
{
    this.btree = btree;
    this.revision = revision;
    this.nbElems = nbElems;
    this.keys = ( KeyHolder[] ) Array.newInstance( KeyHolder.class, nbElems );
}
 
Example 9
Project: parabuild-ci   File: ArrayUtil.java   View Source Code Vote up 5 votes
/**
 * Returns a duplicates of an array.
 */
public static Object duplicateArray(Object source) {

    int size = Array.getLength(source);
    Object newarray =
        Array.newInstance(source.getClass().getComponentType(), size);

    System.arraycopy(source, 0, newarray, 0, size);

    return newarray;
}
 
Example 10
Project: ETF-Java   File: Mapper.java   View Source Code Vote up 5 votes
public <T> T read(ErlangMap data, Class<T> clazz) {
	T instance = ReflectionUtils.createInstance(clazz);
	List<PropertyManager> properties = ReflectionUtils.findProperties(instance, clazz);
	for (PropertyManager property : properties) {
		if (data.containsKey(property.getName())) {
			Object obj = data.get(property.getName());
			if (obj instanceof ErlangMap) {
				obj = read((ErlangMap) obj, property.getSetterType());
			} else if (obj instanceof ErlangList && property.getSetterType().isArray()) {
				if (((ErlangList) obj).size() > 0) {
					Object array = Array.newInstance(property.getSetterType().getComponentType(), ((ErlangList) obj).size());
					for (int i = 0; i < ((ErlangList) obj).size(); i++) {
						Object obj1 = ((ErlangList) obj).get(i);
						if (obj1 != null)
							Array.set(array, i, obj1 instanceof ErlangMap ? read((ErlangMap) obj1, property.getSetterType().getComponentType()) : obj1);
					}
					obj = array;
				} else
					obj = Array.newInstance(property.getSetterType().getComponentType(), 0);
			} else if (obj == null && property.getSetterType().isArray()) {
				obj = Array.newInstance(property.getSetterType().getComponentType(), 0);
			}
			property.setValue(obj);
		}
	}
	return instance;
}
 
Example 11
Project: OpenJSharp   File: IdentityHashMap.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
    int expectedModCount = modCount;
    int size = size();
    if (a.length < size)
        a = (T[]) Array.newInstance(a.getClass().getComponentType(), size);
    Object[] tab = table;
    int ti = 0;
    for (int si = 0; si < tab.length; si += 2) {
        Object key;
        if ((key = tab[si]) != null) { // key present ?
            // more elements than expected -> concurrent modification from other thread
            if (ti >= size) {
                throw new ConcurrentModificationException();
            }
            a[ti++] = (T) new AbstractMap.SimpleEntry<>(unmaskNull(key), tab[si + 1]);
        }
    }
    // fewer elements than expected or concurrent modification from other thread detected
    if (ti < size || expectedModCount != modCount) {
        throw new ConcurrentModificationException();
    }
    // final null marker as per spec
    if (ti < a.length) {
        a[ti] = null;
    }
    return a;
}
 
Example 12
Project: hadoop-oss   File: ArrayWritable.java   View Source Code Vote up 5 votes
public Object toArray() {
  Object result = Array.newInstance(valueClass, values.length);
  for (int i = 0; i < values.length; i++) {
    Array.set(result, i, values[i]);
  }
  return result;
}
 
Example 13
Project: memory-graph   File: IterableUtils.java   View Source Code Vote up 4 votes
@SuppressWarnings("unchecked")
public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type) {
    List<? extends T> list = toList(iterable);
    T[] array = (T[]) Array.newInstance(type, list.size());
    return list.toArray(array);
}
 
Example 14
Project: myfaces-trinidad   File: CopyOnWriteArrayMap.java   View Source Code Vote up 4 votes
private static <K,V> ConcurrentEntry<K,V>[] _addEntryAtIndex(
    ConcurrentEntry<K,V>[] entries, ConcurrentEntry<K,V> entry, int insertIndex, int removeIndex)
{
  int originalSize = entries.length;
  int newSize = originalSize;
  
  // if we haven't hit the LRU limit, increment the size
  if (removeIndex < 0)
    newSize++;

  @SuppressWarnings("unchecked")
  ConcurrentEntry<K,V>[] newEntries = (ConcurrentEntry<K,V>[])
      Array.newInstance(entry.getClass(), newSize);

  if (removeIndex >= 0)
  {
    if (removeIndex == insertIndex)
    {
      // inserting into same spot we removed, so just copy array
      System.arraycopy(entries, 0, newEntries, 0, originalSize);
    }
    else
    {
      if (removeIndex < insertIndex)
      {
        // copy everything before the removeIndex
        System.arraycopy(entries, 0, newEntries, 0, removeIndex);
        
        // copy everything between the removeIndex and the insertIndex, shifting things down
        System.arraycopy(entries, removeIndex + 1, newEntries, removeIndex, insertIndex - removeIndex - 1);
        
        // copy everything from the entry index to the end
        if (insertIndex < originalSize)
        {
          System.arraycopy(entries, insertIndex, newEntries, insertIndex, originalSize - insertIndex);
        }

        // we removed the entry before the insertion location, so decrement to account for this
        insertIndex--;
      }
      else
      {
        // copy everything before the insertIndex
        System.arraycopy(entries, 0, newEntries, 0, insertIndex);

        // copy everything between the insertIndex and the removeIndex, shifting things up
        System.arraycopy(entries, insertIndex, newEntries, insertIndex + 1, removeIndex - insertIndex);
        
        int afterRemoveIndex = removeIndex + 1;
        
        // copy everthing after the removeIndex
        if (afterRemoveIndex < originalSize)
        {
          System.arraycopy(entries, afterRemoveIndex, newEntries, afterRemoveIndex, originalSize - afterRemoveIndex);
        }
      }
    }
  }
  else
  {
    if ((insertIndex == 0) || (insertIndex == originalSize))
    {
      int destStart = (insertIndex == 0) ? 1 : 0;
        
      System.arraycopy(entries, 0, newEntries, destStart, originalSize);
    }
    else
    {
      // copy everything before the insertIndex
      System.arraycopy(entries, 0, newEntries, 0, insertIndex);
      
      // copy everything after the insertIndex
      System.arraycopy(entries, insertIndex, newEntries, insertIndex + 1, originalSize - insertIndex);
    }
  }

  newEntries[insertIndex] = entry;
  
  return newEntries;
}
 
Example 15
Project: fast-list   File: SnappySortedList.java   View Source Code Vote up 4 votes
public SnappySortedList(Class<T> klass, RxSortedListCallback<T> callback, int initialCapacity) {
  mTClass = klass;
  mData = (T[]) Array.newInstance(klass, initialCapacity);
  mCallback = callback;
  mSize = 0;
}
 
Example 16
Project: skript-mirror   File: EvtByReflection.java   View Source Code Vote up 4 votes
@SuppressWarnings("unchecked")
@Override
public boolean init(Literal<?>[] args, int matchedPattern, SkriptParser.ParseResult parseResult) {
  String[] events = ((Literal<String>) args[0]).getArray();

  classes = (Class<? extends Event>[]) Array.newInstance(Class.class, events.length);

  for (int i = 0; i < events.length; i++) {
    String event = events[i];

    try {
      Class<?> eventClass = LibraryLoader.getClassLoader().loadClass(event);

      if (!Event.class.isAssignableFrom(eventClass)) {
        Skript.error(event + " is not an event.");
        return false;
      }

      classes[i] = (Class<? extends Event>) eventClass;
    } catch (ClassNotFoundException e) {
      Skript.error(event + " refers to a non-existent class.");
      return false;
    }
  }

  if (parseResult.mark == 0) {
    priority = SkriptConfig.defaultEventPriority.value();
  } else {
    String priorityName = parseResult.regexes.get(0).group().toUpperCase();
    try {
      priority = EventPriority.valueOf(priorityName);
    } catch (IllegalArgumentException ex) {
      Skript.error(priorityName + " is not a valid priority level.");
      return false;
    }
  }

  for (Class<? extends Event> cls : classes) {
    registerEvent(cls, priority);
  }

  return true;
}
 
Example 17
Project: ProjectAres   File: ArrayUtils.java   View Source Code Vote up 4 votes
/**
 * Create a new array of given size, with the same component type as the given array
 */
public static <T> T[] sameType(T[] array, int size) {
    return (T[]) Array.newInstance(array.getClass().getComponentType(), size);
}
 
Example 18
Project: jdk8u-jdk   File: AWTEventMulticaster.java   View Source Code Vote up 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;
}
 
Example 19
Project: sstore-soft   File: HsqlArrayList.java   View Source Code Vote up 3 votes
public Object[] toArray(int start, int limit) {

        Object[] newArray = (Object[]) Array.newInstance(
            elementData.getClass().getComponentType(), limit - start);

        System.arraycopy(elementData, start, newArray, 0, limit - start);

        return newArray;
    }
 
Example 20
Project: directory-mavibot   File: PersistedNode.java   View Source Code Vote up 3 votes
/**
 * Creates a new Node which will contain only one key, with references to
 * a left and right page. This is a specific constructor used by the btree
 * when the root was full when we added a new value.
 *
 * @param btree the parent BTree
 * @param revision the Node revision
 * @param nbElems The number of elements in this Node
 */
@SuppressWarnings("unchecked")
PersistedNode( BTree<K, V> btree, long revision, int nbElems )
{
    super( btree, revision, nbElems );

    // Create the children array
    children = ( PersistedPageHolder<K, V>[] ) Array.newInstance( PersistedPageHolder.class, nbElems + 1 );
}