Re: Recursive Field Check by Reflection
Tom Anderson wrote:
On Wed, 3 Sep 2008, Eric Sosman wrote:
David wrote:
Getting an object and a field name as a parameter, the code will check
the object fields (including the object's ancestors fields)
recursively to find out if the fields named "X" are null (or any other
given value).
Anybody has an idea where to look for?
Just typed in and not tested:
static boolean isFieldNull(Object obj, String name)
throws Throwable // you could be more specific here
{
Class clown = obj.getClass();
Field field = clown.getDeclaredField(name);
Object value = field.get(obj);
return value == null;
}
Checking for "any other given value" could be a bit more laborious,
depending on how much you can assume about the type of that value.
Can't you just pass in an Object value, and do
value.equals(field.get(obj))? I believe primitive values get boxed, so
this should work for them too.
Yes, field.get(obj) will box primitive fields of the object:
If the field is actually an int, field.get(obj) will return an
Integer object with the same value. I was thinking (perhaps not
too clearly) about supplying the value to be tested against: if
the field is a long containing 42L and the test value is an int 42,
they will box as different types (Long and Integer) and will be
declared unequal, even though `42L == 42' is true. Maybe that's
not a problem for the O.P.
Off-hand I'm not sure whether getDeclaredField() will find fields
that are inherited from superclasses; I think it will but you should
check.
I think it won't. I think the 'declared' means that it only finds fields
declared in that class. getField() will find fields regardless of where
they're declared. The javadoc for getDeclaredField doesn't make this
clear, but that for getField implies it.
You're right: getField() "searches upward," getDeclaredField()
doesn't. On the other hand, getField() can only find public fields,
while getDeclaredField() can handle package-private fields and
perhaps others (I haven't tried).
--
Eric.Sosman@sun.com