Close

Java Reflection - Array.get() Examples

Java Reflection Java Java API 


Class:

java.lang.reflect.Array

java.lang.Objectjava.lang.Objectjava.lang.reflect.Arrayjava.lang.reflect.ArrayLogicBig

Method:

public static Object get(Object array,
                         int index)
                  throws IllegalArgumentException,
                         ArrayIndexOutOfBoundsException

Returns the value of the indexed component in the specified array object. The value is automatically wrapped in an object if it has a primitive type.


Examples


package com.logicbig.example.array;

import java.lang.reflect.Array;

public class GetExample {

public static void main(String... args) {
Object[] arr = {1, 2, 3, "four"};
Object o = Array.get(arr, 2);
System.out.printf("object type: %s, value:%s%n", o.getClass(), o);

o = Array.get(arr, 3);
System.out.printf("object type: %s, value:%s%n", o.getClass(), o);
}
}

Output

object type: class java.lang.Integer, value:3
object type: class java.lang.String, value:four




package com.logicbig.example.array;

import java.lang.reflect.Array;

public class GetExample2 {

public static void main(String... args) {
Object arr = new Object();
Object o = Array.get(arr, 2);
System.out.printf("object type: %s, value:%s%n", o.getClass(), o);
}
}

Output

Caused by: java.lang.IllegalArgumentException: Argument is not an array
at java.base/java.lang.reflect.Array.get(Native Method)
at com.logicbig.example.array.GetExample2.main(GetExample2.java:14)
... 6 more




package com.logicbig.example.array;

import java.lang.reflect.Array;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class GetExample3 {

public static void main(String... args) {
System.out.println(toDelimitedString("java", "-"));
System.out.println(toDelimitedString(new int[]{1, 4, 8}, "-"));

}

public static String toDelimitedString(Object o, String delimiter) {
if (o == null) {
return null;
}
if (o instanceof String) {
return ((String) o).chars()
.mapToObj(c -> Character.toString((char) c))
.collect(Collectors.joining(delimiter));

}
if (o.getClass().isArray()) {
return IntStream.range(0, Array.getLength(o))
.mapToObj(i -> Array.get(o, i))
.map(Objects::toString)
.collect(Collectors.joining(delimiter));
}

throw new IllegalArgumentException("object type not supported: " + o.getClass());
}

}

Output

j-a-v-a
1-4-8




See Also