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);
添加回答
舉報