亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將java類字段轉換為字符串值數組

如何將java類字段轉換為字符串值數組

滄海一幻覺 2022-11-02 17:20:51
我正在尋找一種簡潔優雅的方法來根據變量值將對象變量轉換為數組。例子: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 回答

?
PIPIONE

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


工作示例


查看完整回答
反對 回復 2022-11-02
?
慕虎7371278

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]


查看完整回答
反對 回復 2022-11-02
?
千巷貓影

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);


查看完整回答
反對 回復 2022-11-02
  • 3 回答
  • 0 關注
  • 191 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號