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.classjava.lang.Byte.TYPE == byte.classjava.lang.Short.TYPE == short.classjava.lang.Integer.TYPE == int.classjava.lang.Long.TYPE == long.classjava.lang.Float.TYPE == float.classjava.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
加载中,请稍侯......
精彩评论