1

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.

user373201
  • 10,945
  • 34
  • 112
  • 168

3 Answers3

6

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:


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
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
1

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

user373201
  • 10,945
  • 34
  • 112
  • 168
0

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

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 1
    isPrimitive() on java.lang.Integer returns false not true – user373201 Mar 01 '11 at 15:14
  • 3
    Irrelevant. Integer.TYPE == int.class as pointed out by Matt Ball. 'int' is a primitive, and isPrimitive() will return 'true' for it. Integer.TYPE is *not* Integer.class. – user207421 Mar 01 '11 at 22:09