通过反射迭代数组 [英] Iterating over arrays by reflection
本文介绍了通过反射迭代数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在做一些反思工作并遇到一些小问题。
I am doing some reflection work and go to a little problem.
我正在尝试将对象打印到某个GUI树,并且以通用方式检测数组有问题。
I am trying to print objects to some GUI tree and have problem detecting arrays in a generic way.
我建议:
对象instanceof Iterable
object instanceof Iterable
会成功,但事实并非如此(显然只适用于Lists和Set以及任何实现它的人。)
Would make the job ,but it does not, (obviously applies only to Lists and Set and whoever implements it.)
那么我怎么会认出一个数组对象[]
,或者 long []
或长[]
..?
So how is that i would recognice an Array Some Object[]
, Or long[]
or Long[]
.. ?
谢谢
推荐答案
如果您不想只检查对象是否是数组,还要迭代它:
If you don't want only to check whether the object is an array, but also to iterate it:
if (array.getClass().isArray()) {
int length = Array.getLength(array);
for (int i = 0; i < length; i ++) {
Object arrayElement = Array.get(array, i);
System.out.println(arrayElement);
}
}
(上面的类是 java.lang.reflect.Array
)
这篇关于通过反射迭代数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文