开发者

find fields of type String, Boolean, Integer using reflection

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 isPrimiti开发者_高级运维ve method for char, byte, short etc.


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

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:

  • Field#getType()
  • Class#isPrimitive() (though it sounds like you already know about this one)

Edit

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

  • 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


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


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

ClassUtils.isPrimitiveOrWrapper(field.getType()) 

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜