java 通过反射迭代数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2200399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterating over arrays by reflection
提问by Roman
I am doing some reflection work and go to a little problem.
我正在做一些反思工作并解决一个小问题。
I am trying to print objects to some GUI tree and have problem detecting arrays in a generic way.
我正在尝试将对象打印到某个 GUI 树,但在以通用方式检测数组时遇到问题。
I suggested that :
我建议:
object instanceof Iterable
Iterable 的对象实例
Would make the job ,but it does not, (obviously applies only to Lists and Set and whoever implements it.)
会做这份工作,但它不会,(显然只适用于 Lists 和 Set 以及实现它的人。)
So how is that i would recognice an Array Some Object[], Or long[]or Long[].. ?
那么我如何识别数组 Some Object[], Orlong[]或Long[].. ?
Thanks
谢谢
回答by Bozho
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);
}
}
(the class above is java.lang.reflect.Array)
(上面的类是java.lang.reflect.Array)
回答by Joonas Pulakka
Do you mean Object.getClass().isArray()?
你的意思是Object.getClass().isArray()?
回答by u7867
You can do
你可以做
if (o instanceof Object[]) {
Object[] array = (Object[]) o;
// now access array.length or
// array.getClass().getComponentType()
}
回答by sfussenegger
First of all, @Bozho's answer is perfectly correct.
首先,@Bozho 的回答是完全正确的。
If you want to make this to be easier useable, I've just created a method in our little OSS utility molindo-utilsthat turns an array of unknown type into an Iterable: ArrayUtils.toIterable(Object)
如果你想让它更容易使用,我刚刚在我们的小 OSS 实用程序 molindo-utils中创建了一个方法,它将未知类型的数组转换为可迭代的:ArrayUtils.toIterable(Object)
This way, you can do:
这样,您可以执行以下操作:
// any array, e.g. int[], Object[], String[], ...
Object array = ...;
for (Object element : ArrayUtils.toIterable(array)) {
// element of type Integer for int[]
System.out.println(element);
}
See README of molindo-utilson how to get molindo-utils or feel free to copy the code if you like, just as you see fit.
请参阅molindo-utils 的README 以了解如何获取 molindo-utils,或者如果您愿意,可以随意复制代码,就像您认为合适的那样。

