Java Reflection Java Java API
Class:
java.lang.reflect.Array
Methods:
public static Object newInstance(Class<?> componentType,
int length)
throws NegativeArraySizeException
Creates a new array with the specified component type and length.
The number of dimensions of the new array must not exceed 255.
public static Object newInstance(Class<?> componentType,
int... dimensions)
throws IllegalArgumentException,
NegativeArraySizeException
Creates a new array with the specified component type and dimensions.
The number of dimensions of the new array must not exceed 255.
Examples
package com.logicbig.example.array;
import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays;
public class NewInstanceExample {
public static void main(String... args) { int len = 4; Object o = Array.newInstance(BigDecimal.class, len); for (int i = 0; i < len; i++) { Array.set(o, i, BigDecimal.valueOf(i)); } System.out.println(Arrays.toString((Object[]) o)); } }
Output[0, 1, 2, 3]
package com.logicbig.example.array;
import java.lang.reflect.Array; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.stream.IntStream;
public class NewInstanceExample2 {
public static void main(String... args) { List<String> list = Arrays.asList("one", "two", "three"); String[] strings = toArray(list, String.class); System.out.println(Arrays.toString(strings)); }
public static <T> T[] toArray(Collection<T> c, Class<T> type) { if (c == null) { return null; } Object o = Array.newInstance(type, c.size()); Iterator<T> iterator = c.iterator(); IntStream.range(0, c.size()) .forEach(i -> Array.set(o, i, iterator.next())); @SuppressWarnings("unchecked") T[] ts = (T[]) o; return ts; } }
Output[one, two, three]
Creating multidimensional arrays package com.logicbig.example.array;
import java.lang.reflect.Array; import java.util.Arrays;
public class NewInstanceExample3 {
public static void main(String... args) { int d1 = 2; int d2 = 3; Object mainArray = Array.newInstance(int.class, d1, d2); for (int i = 0; i < d1; i++) { Object childArray = Array.newInstance(int.class, d2); Array.set(mainArray, i, childArray); for (int j = 0; j < d2; j++) { Array.set(childArray, j, i + j); } }
String s1 = Arrays.deepToString((Object[]) mainArray); System.out.println(s1); } }
Output[[0, 1, 2], [1, 2, 3]]
|
|