首页 > 解决方案 > 用java中的反射检查一个字段是真还是假

问题描述

目前正在尝试编写一些菜单功能,并想知道是否有办法找出布尔字段是真还是假。这是我目前正在尝试的代码,但出现错误

try{

     field = a.getClass().getField(b); 

     if(toggle==1&&field){
     }else if(toggle==1&&!field){
       field.set(a, true);
     }else if(toggle==0&&!field){
     }else if(toggle==0&&field){
       field.set(a, false);
     }
}catch (NullPointerException e) {
}catch (NoSuchFieldException e) {
}catch (IllegalAccessException e) {
}

错误是

The operator && is undefined for the argument type(s) boolean, Field

标签: javareflectionbooleanfield

解决方案


您需要根据实例获取字段的值。

boolean value = field.getBoolean(instance);

推荐阅读