【问题标题】:Is there a way to find if a Field is boolean the same as isPrimitive()?有没有办法找到一个字段是否与 isPrimitive() 相同的布尔值?
【发布时间】:2012-02-10 11:10:26
【问题描述】:

有没有办法在 Java 反射中查找字段是否为 booleanisPrimitive() 相同?

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;
 }
}

【问题讨论】:

    标签: java class reflection boolean


    【解决方案1】:
    if(fld.getType().equals(boolean.class))
    

    刚刚对此进行了测试,它适用于原始 boolean 变量。

    【讨论】:

      【解决方案2】:

      我相信Boolean.class.isAssignableFrom(fld.getClass()) 可用于确定该字段是否为布尔值。不过,我还没有机会测试这是否适用于原语。

      【讨论】:

      • 这不适用于原始布尔值。但是,如果您使用的是 Spring,则可以调用 ClassUtils.isAssignable(Boolean.class, fld.getClass()),如果 fld 是布尔值或布尔值,这应该可以工作。
      • Thor84no:执行此操作时出现此错误:Class 类型中的方法 isAssignableFrom(Class>) 不适用于参数 (Boolean)
      • Dan Robinson:ClassUtils 也没有帮助:ClassUtils 类型中的方法 isAssignable(Class>, Class>) 不适用于参数(Class, Boolean)
      • 我相信应该有一个 boolean.class 涵盖原语(我认为从 Java 6 开始)。您可以将这两个 Boolean.class.isAssignableFrom(fld.getClass()) || boolean.class.isAssignableFrom(fld.getClass()) 结合起来。不过我没有 IDE 方便的 atm。
      【解决方案3】:

      试试这个 (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.
      

      【讨论】:

        【解决方案4】:

        这是用于原始和对象:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-01-11
          • 2012-07-01
          • 2013-09-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多