英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论