I am playing with Java's reflection API, and I'm writing methods that inspect a given object and describes its fields, methods, and so on.
I am using the getFields()
method to iterate on the different attributes and display the object contents:
public static void display(Integer i)
{
System.out.println("An integer: " + i);
}
// Basically a method for each primitive type wrapper
public static void display(Object o)
{
for (Field f : c.getFields())
{
System.out.println("A " + o.getClass() + " which is composed of:");
display(f.get(o));
}
}
(Other primitive types and arrays omitted for simplicity's sake.)
Eventhough Field
's get
method returns an Object
, I thought the right methods would be called for the primitive type wrappers (Integers, Strings, etc.), but actually, only display(Object o)
is called (no implicit downcasting is performed).
For now, the only solution I have found is to brutally downcast the objects if possible like this:
public static void display(Object o)
{
if (o instanceof Integer)
{
display((Integer) o);
return;
}
else if (o instanceof String
{
...
} // And so on
for (Field f : c.getFields())
{
System.out.println("A " + o.getClass() + " which is composed of:");
display(f.get(o));
}
}
This does however seem ugly, and I was wondering if there was a more elegant way to make sure the right method is called. Any ideas?
Thanks in advance, good people from StackOverflow!