java通过数组字段而不创建新实例

时间:2014-11-21 20:02:15

标签: java reflection

我想写一个方法来获取Object并用Object的字段做一些逻辑。

我的方法如下:

public void exampleCast(Object obj) {
    Field[] fields = obj.getClass().getFields();
    for (Field field : fields) {                    
        if (field.getClass().isArray()) {

        /*
            HOW CAN I GO OVER THE ARRAY FIELDS , WITHOUT CREATING NEW INSATCNE ?
            SOMETHING LIKE:
            for (int i = 0; i < array.length; i++) {
               array[i] ...
            }

        */  
        } else {
            ...
            ...
        }
    }
}   

对象的例子:

class TBD1 {
 public int x;
 public int y;
 public int[] arrInt = new int[10];
 public byte[] arrByte = new byte[10];
}

并致电我的方法:

TBD1 tbd1 = new TBD1();
exampleCast(tbd1);

在我的方法中,我不知道如何在不创建新实例的情况下获取数组值(使用“newInstance”方法) 可能吗 ? (请参阅我在我的例子中写的评论)

我读了这两个网站: http://jroller.com/eyallupu/entry/two_side_notes_about_arrays

http://tutorials.jenkov.com/java-reflection/arrays.html

但是没有得到我想要的东西。

请帮忙:) 感谢

1 个答案:

答案 0 :(得分:3)

如果我理解您的问题,您可以使用java.lang.reflect.Array之类的内容

if (field.getType().isArray()) { // <-- should be getType(), thx @Pshemo
    Object array = field.get(obj);
    int len = Array.getLength(array);
    for (int i = 0; i < len; i++) {
        Object v = Array.get(array, i);
        System.out.println(v);
    }
} // ...
相关问题