Is there a way to find if a Field is boolean the same as isPrimitive()?
14,879
Solution 1
if(fld.getType().equals(boolean.class))
Just tested this and it works for primitive boolean
variables.
Solution 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.
Solution 3
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.
Author by
nabil
Updated on June 05, 2022Comments
-
nabil almost 2 years
Is there a way to find if a Field is
boolean
in Java reflection the same asisPrimitive()
?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; } }