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

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

Check if a field is true or false with reflections in java

问题

  1. 目前正在尝试编写一些菜单功能,并想知道是否有办法找出布尔字段的值是真还是假。这是我目前尝试的代码,但是我得到了一个错误:
  2. try{
  3. field = a.getClass().getField(b);
  4. if(toggle==1&&field){
  5. }else if(toggle==1&&!field){
  6. field.set(a, true);
  7. }else if(toggle==0&&!field){
  8. }else if(toggle==0&&field){
  9. field.set(a, false);
  10. }
  11. }catch (NullPointerException e) {
  12. }catch (NoSuchFieldException e) {
  13. }catch (IllegalAccessException e) {
  14. }
  15. 错误是:
  16. 对于参数类型 booleanField,运算符 && 未定义
英文:

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

  1. try{
  2. field = a.getClass().getField(b);
  3. if(toggle==1&&field){
  4. }else if(toggle==1&&!field){
  5. field.set(a, true);
  6. }else if(toggle==0&&!field){
  7. }else if(toggle==0&&field){
  8. field.set(a, false);
  9. }
  10. }catch (NullPointerException e) {
  11. }catch (NoSuchFieldException e) {
  12. }catch (IllegalAccessException e) {
  13. }

The error is

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

答案1

得分: 1

根据实例获取字段的值。

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

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

  1. 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:

确定