12

Is there a way to find if a Field is boolean in Java reflection the same as isPrimitive()?

Field fieldlist[] = clazz.getDeclaredFields();
for (int i = 0; fieldlist.length & gt; i; i++) {
 Field fld = fieldlist[i];
 if (fld.getClass().isPrimitive()) {
  fld.setInt(object, 0);
  continue;
 }
}
Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
nabil
  • 904
  • 3
  • 12
  • 28

4 Answers4

33
if(fld.getType().equals(boolean.class))

Just tested this and it works for primitive boolean variables.

Tudor
  • 61,523
  • 12
  • 102
  • 142
2

I believe Boolean.class.isAssignableFrom(fld.getClass()) can be used to determine if the field is a boolean. I haven't had a chance to test whether this works for primitives though.

Vala
  • 5,628
  • 1
  • 29
  • 55
  • This shouldn't work for primitive booleans. If you're using Spring, you can call ClassUtils.isAssignable(Boolean.class, fld.getClass()), though, and that should work if fld is boolean or Boolean. – Dan Robinson Apr 05 '13 at 04:35
  • Thor84no: I got this error while doing that: The method isAssignableFrom(Class>) in the type Class is not applicable for the arguments (Boolean) – Akshaya Aradhya Jul 11 '14 at 00:09
  • Dan Robinson: ClassUtils didn't help either: The method isAssignable(Class>, Class>) in the type ClassUtils is not applicable for the arguments (Class, Boolean) – Akshaya Aradhya Jul 11 '14 at 00:14
  • I believe there should be a `boolean.class` that covers primitives (from Java 6 onward I think). You could combine the two `Boolean.class.isAssignableFrom(fld.getClass()) || boolean.class.isAssignableFrom(fld.getClass())`. I don't have an IDE handy atm though. – Vala Jul 11 '14 at 09:30
1

Try this (reference):

public boolean getBoolean(Object obj)
               throws IllegalArgumentException,
                      IllegalAccessException

Gets the value of a static or instance boolean field.

Parameters:
    obj - the object to extract the boolean value from 
Returns:
    the value of the boolean field 
Throws:
    IllegalAccessException - if the underlying field is inaccessible. 
    IllegalArgumentException - if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof), **or if the field value cannot be converted to the type boolean** by a widening conversion. 
    NullPointerException - if the specified object is null and the field is an instance field. 
    ExceptionInInitializerError - if the initialization provoked by this method fails.
Garrett Hyde
  • 5,409
  • 8
  • 49
  • 55
dantuch
  • 9,123
  • 6
  • 45
  • 68
0

This is for primitive and object:

boolean isBooleanType = field.getType().equals(boolean.class) || field.getType().equals(Boolean.class);
WhatsThePoint
  • 3,395
  • 8
  • 31
  • 53