Forums Register Login
reflection to get values in an interface
I have been playing around with reflection and have run into a problem.
I have a interface with the following:
public static final String personCollectionHeadings[] = new String[] {"personID", "memberType",
"firstName", "middleName", "lastName",
"birthDate", "statusCode", "joinDate" };
final double version = 0.1;

I'm tring to use reflection to get the value of the string array, I can get a value of a
double but when I just can't the arrays value.
The code I tring to use is this:

public static String dumpField(Field f) {
Class c = f.getClass();
try {
return ":FIELD TOSTRING>"+f.toString()
+ ":CLASS TOSTRING>"+ c.toString()
+":>"+ "\n";
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
return "ERROR IllegalArgumentException";
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
return "ERROR IllegalAccessException";

When I run this for the double and String[] I get:
:FIELD TOSTRING>public static final double Tracker.ITrackerPerson.version:CLASS TOSTRING>class java.lang.reflect.Field:GET>0.1:GETDECLARINGCLASS>interface Tracker.ITrackerPerson:GETTYPE>double:GETNAME>version:>
:FIELD TOSTRING>public static final java.lang.String[] Tracker.ITrackerPerson.personCollectionHeadings:CLASS TOSTRING>class java.lang.reflect.Field:GET>[Ljava.lang.String;@1ba94d:GETDECLARINGCLASS>interface Tracker.ITrackerPerson:GETTYPE>class [Ljava.lang.String;:GETNAME>personCollectionHeadings:>

So I can get the value of the double with the get method but how can I get the String[]?
If you print an array (which calls toString() behind the covers) then you get a String like [Ljava/lang/String;@12876287 . That's the "Value" of the array.

You mean how to you get the contents? Well, either cast the Object from get() to a String[], or, if this is all automated, have a looksee at the class java.lang.reflect.Array -- the static methods in that class will help you tremendously. Also handy will be java.lang.Class.isArray(), which your method can call to determine when to pull java.lang.reflect.Array out of its holster.

I'm using f.getType().isArray() to determine how to use the field.

Thanks again!

This thread has been viewed 2338 times.

All times above are in ranch (not your local) time.
The current ranch time is
Dec 15, 2018 17:46:23.