简体   繁体   中英

In Java is there any way to tell if a class is a simple 'Java' class?

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 :

  1. Trial and error to list them all individually - hoping that two years in the future I don't add another attribute of a type I haven't used before (Yuck!)
  2. See if the class name begins with the string java. (double Yuck!)

Please tell me I missed a nice utility class/method somewhere.

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. .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM