简体   繁体   English

在Java中,有什么方法可以判断一个类是否是简单的“ Java”类?

[英]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... 我以为这样可以,但是后来我发现String并不是'PrimitiveOrWrapper'。...然后我发现Date也不是...然后我发现BigDecimal也不是...

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. 我只想知道一个类是内部的/本机的/普通的/简单的/基本的Java类还是我编写的复杂对象。 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. 查看类名称是否以字符串java开头 (double Yuck!) (双重Y!)

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. 没有单个API调用可以告诉您该对象是否在内部。

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. 第二个isArrayisArray ,因为有一个特殊的方法可以返回数组的组件类型。 Lastly getPackage can be used to answer the question, is this object part of the JDK family or not. 最后,可以使用getPackage回答问题,这个对象是否属于JDK系列。 All public Java API packages start with java. 所有公共Java API软件包java.开头java. or javax. javax. and private Java APIs start with sun. 私有Java API从sun.开始sun. .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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