• Post Reply Bookmark Topic Watch Topic
  • New Topic

Reflection: Reading an array field  RSS feed

 
Jeffies Shah
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I am using Reflection (java 1.4.2) to read an object and display its instance variables and the values they hold. I am facing a problem with reading instance variables of type array. The difficulty is explained below:

if( field.getType().isArray() ) {
Objecy obj = field.getObj();

//The obj can be an array of a primitive or any
//reference type. Now, how will typecast the object in
//a generic way and display the contents of the array obj?
}

Thanks for your time,
Jaffer J Shah.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, there is no such method as getObj. The reason is quite simple - any (non-static) field does not have one single instance but one instance per object instance. All object instances share the same field. That's why all the get methods of Field take an object - the instance you want the field value of.

Getting back to your problem: Class has a method called getComponentType which will return Integer.TYPE or int.class for int[], String.class for String[], etc. Depending on the type you can then handle the specifics using java.reflect.Array.
 
Ashok Kumar Babu
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am using Reflection (java 1.4.2) to read an object and display its instance variables and the values they hold. I am facing a problem with reading instance variables of type array.


How about this below code?

 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ashok Kumar Babu:

Please cache the fields. PLEASE! Now you retrieve all fields twice times the number of fields!

So instead:

Now a huge error in your code:

And what if the field indicates an int[], or boolean[]? ClassCastException!

That's why you need getComponentType as well:


Fortunately, java.lang.reflect.Array can help you out without all these checks:

element will be Integer, Boolean etc for primitive type arrays.
[ September 23, 2008: Message edited by: Rob Prime ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!