Reputation: 563
I'm using reflection to read through some class objects I've created and using recursion to trace down through the entire object tree.
The problem I have is that when I have a 'Field' I need to know if it's a simple attribute or another complex object. The former can just be processed immediately, but the latter I need to dig into and call the recursive method again. My code is something like this :
recurse(Object o) {
Class clazz = o.getClass();
for (Field f : clazz.getDeclaredFields() ) {
fieldClass = f.getType();
// Heres the broken part
if ( !ClassUtils.isPrimitiveOrWrapper(fieldClass) ) {
recurse(f.get(o));
}
else {
// Process simple attribute
}
}
}
I thought this would work, but then I found that String is not a 'PrimitiveOrWrapper'.... then I found that Date isn't either... then I found that BigDecimal isn't either...
Is there really NO class or utility package that can handle this request? All I want is to know if a Class is an internal / native / plain / simple / basic Java class or a complex object that I've written. This shouldn't be hard.
I believe my choices are :
Please tell me I missed a nice utility class/method somewhere.
Upvotes: 5
Views: 1337
Reputation: 11917
There is no single API call that will tell you whether the object is internal or not.
You can however use the following methods:
isPrimitive
isArray
getPackage
The first one is fairly straight forward. The second, isArray
is needed as there is a special method which will return the component type of the array. Lastly getPackage
can be used to answer the question, is this object part of the JDK family or not. All public Java API packages start with java.
or javax.
and private Java APIs start with sun.
.
Upvotes: 2