I'm trying to determine the type of a field on an object. I don't know the type of the object when it is passed to me but I need to find fields which are long
s. It is easy enough to distinguish the boxed Long
s but the primitive long
seems more difficult.
I can make sure that the objects passed to me only have Longs
, not the primitives, but I'd rather not. So what I have is:
for (Field f : o.getClass().getDeclaredFields()) {
Class<?> clazz = f.getType();
if (clazz.equals(Long.class)) {
// found one -- I don't get here for primitive longs
}
}
A hacky way, which seems to work, is this:
for (Field f : o.getClass().getDeclaredFields()) {
Class<?> clazz = f.getType();
if (clazz.equals(Long.class) || clazz.getName().equals("long")) {
// found one
}
}
I'd really like a cleaner way to do this if there is one. If there is no better way then I think that requiring the objects I receive to only use Long
(not long
) would be a better API.
Any ideas?