I'm tring to write a method which get Object and do some logic with the Object's Fields.
My method looks like:
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 {
...
...
}
}
}
And example for objects:
class TBD1 {
public int x;
public int y;
public int[] arrInt = new int[10];
public byte[] arrByte = new byte[10];
}
And call to my method:
TBD1 tbd1 = new TBD1();
exampleCast(tbd1);
In my mehod I dont know how can I get the array values without create new instance (using "newInstance" method) Is it possible ? (please see the comment I wrote in my example)
I read those 2 web sites: http://jroller.com/eyallupu/entry/two_side_notes_about_arrays
http://tutorials.jenkov.com/java-reflection/arrays.html
But didnt get what I want to.
Please help :) Thanks
If I understand your question, you might use java.lang.reflect.Array
and something like
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);
}
} // ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.