使用Java的反射检查字段是否为真或假

huangapple go评论82阅读模式
英文:

Check if a field is true or false with reflections in 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) {
    }
错误是:

    对于参数类型 boolean、Field,运算符 && 未定义
英文:

Currently trying to code some menu functionality and wondered if there’s a way to find out if a boolean field is true or false. This is the code I’m currently trying but I get an error

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 error is

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

答案1

得分: 1

根据实例获取字段的值。

boolean value = field.getBoolean(instance);
英文:

You need to get the value of the field based on an instance.

boolean value = field.getBoolean(instance);

答案2

得分: 1

a.getClass().getField(b); 返回 java.lang.reflect.Field;,不是布尔类型。

您可以使用 field.getBoolean(a) 来获取布尔值。

英文:

a.getClass().getField(b); return java.lang.reflect.Field;, not a boolean type.

You could use field.getBoolean(a) which get a boolean value.

答案3

得分: 0

Class.getField(String)返回一个java.lang.reflect.Field。您将希望使用该a作为参数调用getBoolean。请注意,您假设该字段是公共的,这可能不是一个好主意。此外,反射通常不是一个很好的想法。

英文:

Class.getField(String) returns a java.lang.reflect.Field. You will want to call getBoolean with that a as an argument. Note that you are assuming that the field is public, which probably isn't a great idea. Also reflection is usually a really bad idea.

huangapple
  • 本文由 发表于 2020年3月16日 09:07:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/60699239.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定