Iterating over arrays by reflection

前端 未结 4 1493
广开言路
广开言路 2020-12-25 11:14

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.

4条回答
  •  猫巷女王i
    2020-12-25 12:16

    First of all, @Bozho's answer is perfectly correct.

    If you want to make this to be easier useable, I've just created a method in our little OSS utility molindo-utils that turns an array of unknown type into an Iterable: 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-utils on how to get molindo-utils or feel free to copy the code if you like, just as you see fit.

提交回复
热议问题