3 回答
TA贡献1829条经验 获得超9个赞
假设没有吸气剂,您可以使用反射:
Subject subject = new Subject(true, true, true, false, false);
Field[] fields = Subject.class.getDeclaredFields(); // Get the object's fields
List<String> result = new ArrayList<>();
Object value;
for(Field field : fields) { // Iterate over the object's fields
field.setAccessible(true); // Ignore the private modifier
value = field.get(subject); // Get the value stored in the field
if(value instanceof Boolean && (Boolean)value) { // If this field contains a boolean object and the boolean is set to true
result.add(field.getName()); // Add the field name to the list
}
}
System.out.println(result); // ["music", "food", "sport"]
TA贡献1802条经验 获得超4个赞
对于一般解决方案,您可以为此使用反射和 Java Streams:
Subject subject = new Subject(true, true, true, false, false);
String[] trueFields = Arrays.stream(subject.getClass().getDeclaredFields())
.filter(f -> {
f.setAccessible(true);
try {
return f.getBoolean(subject);
} catch (IllegalAccessException e) {
return false;
}
})
.map(Field::getName)
.toArray(String[]::new);
结果将是:
[music, food, sport]
TA贡献1829条经验 获得超7个赞
您可以使用java的反射来实现这一点
List<String> output = new ArrayList<>();
for(Field f:s.getClass().getDeclaredFields()) {
if((f.getType().equals(boolean.class) || f.getType().equals(Boolean.class)) && f.getBoolean(s)) {
output.add(f.getName());
}
}
System.out.println(output);
添加回答
举报