gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:36:33 25 4
gpt4 key购买 nike

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

例子:

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;

}

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

例子:新主题(真,真,真,假,假)

预期结果:["音乐", "食物", "运动"]

最佳答案

假设没有 setter/getter ,你可以使用反射:

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

关于java - 如何将 java 类字段转换为字符串值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55942710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com