java 使用反射查找字符串、布尔值、整数类型的字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5148195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:42:26  来源:igfitidea点击:

find fields of type String, Boolean, Integer using reflection

java

提问by user373201

Is there a way to find fields in a class that are of the Type

有没有办法在类型的类中查找字段

    java.lang.Character.TYPE
    java.lang.Byte.TYPE
    java.lang.Short.TYPE
    java.lang.Integer.TYPE
    java.lang.Long.TYPE
    java.lang.Float.TYPE
    java.lang.Double.TYPE

there is a isPrimitive method for char, byte, short etc.

有一个用于 char、byte、short 等的 isPrimitive 方法。

采纳答案by user373201

I was looking for one method that would return true for wrapper types. Springs ClassUtils provides one such method

我正在寻找一种可以为包装器类型返回 true 的方法。Springs ClassUtils 提供了一种这样的方法

ClassUtils.isPrimitiveOrWrapper(field.getType()) 

returns true for all of the above that I requested, except String

对我请求的所有上述内容返回 true,除了 String

回答by Matt Ball

You can start with Class#getDeclaredFields()to get an array of the fields in your class. Then, iterate over each Fieldin the array and filter as needed.

您可以从Class#getDeclaredFields()获取类中的字段数组开始。然后,遍历Field数组中的每一个并根据需要进行过滤。

Something like this:

像这样的东西:

public static List<Field> getPrimitiveFields(Class<?> clazz)
{
    List<Field> toReturn = new ArrayList<Field>();

    Field[] allFields = clazz.getDeclaredFields();

    for (Field f : allFields)
    {
        Class<?> type = f.getType();
        if (type.isPrimitive())
        {
            toReturn.add(f);
        }
    }

    return toReturn;
}

More info:

更多信息:



Edit

编辑

It might be worth clarifying that the types java.lang.Character.TYPE, etc., are the same thing as the class literals. That is,

可能值得澄清的是 typesjava.lang.Character.TYPE等与类文字是一样的。那是,

  • java.lang.Character.TYPE == char.class
  • java.lang.Byte.TYPE == byte.class
  • java.lang.Short.TYPE == short.class
  • java.lang.Integer.TYPE == int.class
  • java.lang.Long.TYPE == long.class
  • java.lang.Float.TYPE == float.class
  • java.lang.Double.TYPE == double.class
  • java.lang.Character.TYPE == char.class
  • java.lang.Byte.TYPE == byte.class
  • java.lang.Short.TYPE == short.class
  • java.lang.Integer.TYPE == int.class
  • java.lang.Long.TYPE == long.class
  • java.lang.Float.TYPE == float.class
  • java.lang.Double.TYPE == double.class

回答by user207421

Those types are all primitives, so use isPrimitive().

这些类型都是原语,所以使用 isPrimitive()。