如何遍历 Object 引用的数组?

我有一个基于标识字符串get(String)返回 的函数。Object


有时,Object返回的get是一个数组。如果是这样,我想遍历每个数组元素并以某种方式处理该元素。类似于下面的代码。


 Object object = get(identifier);

 if(object.getClass().isArray())

      processArray(object);


 void processArray(Object array) {

    //For each element in the array, do something

 }

我尝试的解决方案是这样的


 void processArray(Object array) {

      Object[] arrayCasted  = (Object[]) array;

      for(Object arrayElement : arrayCasted)

           //Process each element somehow 

 }

但这仅适用于对象数组(而不适用于原始数组)


 Integer[] test1 = {1, 2, 3};

 int[] test2 = {1, 2, 3};

 processArray(test1); //Works

 processArray(test2); //Does not work: ClassCastException

有没有办法processArray为所有阵列工作?


繁华开满天机
浏览 145回答 1
1回答

翻阅古今

使用java.lang.reflect.Array是关键。如果你有一个Objectwhich 实际上是某种类型的数组(原始类型、字符串或某种自定义类型等),你可以在不知道其类型或进行类型转换等的情况下迭代、打印等。Object[]无法进行类型转换,因为元素不是类型Object,但您可以通过了解其组件类型 (&nbsp;obj.getClass().getComponentType()) 来类型转换为特定类型的数组。但是,java.lang.reflect.Array基于解决方案要干净得多。import java.lang.reflect.Array;public class ArrayOfUnknownType {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; int[] i = {1, 2, 3};&nbsp; &nbsp; &nbsp; &nbsp; String[] s = {"a", "b", "c"};&nbsp; &nbsp; &nbsp; &nbsp; Dog[] d = {new Dog("d"), new Dog("e")};&nbsp; &nbsp; &nbsp; &nbsp; process(i);&nbsp; &nbsp; &nbsp; &nbsp; process(s);&nbsp; &nbsp; &nbsp; &nbsp; process(d);&nbsp; &nbsp; }&nbsp; &nbsp; private static void process(Object data) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(data.getClass().getComponentType());&nbsp; &nbsp; &nbsp; &nbsp; if(data.getClass().isArray()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int length = Array.getLength(data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int count =0; count < length; count++ ){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(Array.get(data, count));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; private static class Dog {&nbsp; &nbsp; &nbsp; &nbsp; public String name;&nbsp; &nbsp; &nbsp; &nbsp; public Dog(String name) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.name = name;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public String toString() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return "Dog{" +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "name='" + name + '\'' +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '}';&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java