Подтвердить что ты не робот

Есть ли способ узнать, является ли Field логическим значением, аналогичным isPrimitive()?

Есть ли способ узнать, является ли Поле boolean в отражении Java так же, как 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;
 }
}
4b9b3361

Ответ 1

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

Просто проверил это, и он работает для примитивных переменных boolean.

Ответ 2

Я считаю, что Boolean.class.isAssignableFrom(fld.getClass()) может использоваться, чтобы определить, является ли поле логическим. У меня не было возможности проверить, работает ли это для примитивов.

Ответ 3

Попробуйте (ссылка):

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.

Ответ 4

Это для примитива и объекта:

boolean isBooleanType = field.getType().equals(boolean.class) || field.getType().equals(Boolean.class);