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

我正在寻找一种简洁优雅的方法来根据变量值将对象变量转换为数组。


例子:


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


沧海一幻觉
浏览 156回答 3
3回答

PIPIONE

假设没有吸气剂,您可以使用反射:Subject subject = new Subject(true, true, true, false, false);Field[] fields = Subject.class.getDeclaredFields();&nbsp; &nbsp;// Get the object's fieldsList<String> result = new ArrayList<>();Object value;for(Field field : fields) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Iterate over the object's fields&nbsp; &nbsp; field.setAccessible(true);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Ignore the private modifier&nbsp; &nbsp; value = field.get(subject);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Get the value stored in the field&nbsp; &nbsp; if(value instanceof Boolean && (Boolean)value) {&nbsp; // If this field contains a boolean object and the boolean is set to true&nbsp; &nbsp; &nbsp; &nbsp; result.add(field.getName());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Add the field name to the list&nbsp; &nbsp; }}System.out.println(result); // ["music", "food", "sport"]工作示例

慕虎7371278

对于一般解决方案,您可以为此使用反射和 Java Streams:Subject subject = new Subject(true, true, true, false, false);String[] trueFields = Arrays.stream(subject.getClass().getDeclaredFields())&nbsp; &nbsp; &nbsp; &nbsp; .filter(f -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; f.setAccessible(true);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return f.getBoolean(subject);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (IllegalAccessException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; .map(Field::getName)&nbsp; &nbsp; &nbsp; &nbsp; .toArray(String[]::new);结果将是:[music, food, sport]

千巷猫影

您可以使用java的反射来实现这一点&nbsp;List<String> output =&nbsp; new ArrayList<>();&nbsp; &nbsp; for(Field f:s.getClass().getDeclaredFields()) {&nbsp; &nbsp; &nbsp; &nbsp; if((f.getType().equals(boolean.class) || f.getType().equals(Boolean.class)) && f.getBoolean(s)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output.add(f.getName());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(output);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java