如何将Java类字段转换为字符串值的数组

时间:2019-05-01 21:06:31

标签: java arrays

我正在寻找一种干净优雅的方法,可以根据变量值将对象变量转换为数组。

示例:

public class Subject {

    public Subject(boolean music, boolean food, boolean sport, boolean business, boolean art) {
        this.music = music;
        this.food = food;
        this.sport = sport;
        this.business = business;
        this.art = art;
    }

    private final Long id;
    private final boolean music;
    private final boolean food;
    private final boolean sport;
    private final boolean business;
    private final boolean art;

}

基于每个字段的值,我想将字段名称作为字符串添加到数组中。

示例: new Subject(true, true, true, false, false)

预期结果: ["music", "food", "sport"]

3 个答案:

答案 0 :(得分:4)

假设没有吸气剂,则可以使用反射:

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"]


Working example

答案 1 :(得分:2)

对于一般解决方案,您可以为此使用反射和Java流:

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]

答案 2 :(得分:2)

您可以使用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);