【问题标题】:How to get object's fields as comma separated string or a list in java如何在java中将对象的字段作为逗号分隔的字符串或列表获取
【发布时间】:2021-08-16 20:51:03
【问题描述】:

我正在尝试将对象的属性作为列表获取。比如:

class Sample {

  private String type;
  private String name;
  private int value;
  
  // getter-setter
}

预期输出: {"type", "name", "value"}

有没有一种编程方式来做到这一点?

【问题讨论】:

  • 尝试引用link

标签: java string list properties instance


【解决方案1】:

你可以使用 Java 反射

public static String getClassProperties(Class<?> clazz) {
    return Arrays.stream(clazz.getDeclaredFields()).map(field -> "\"" + field.getName() + "\"").collect(Collectors.joining(", ", "{", "}"));
}

使用示例:

public static void main(String[] args) {
    System.out.println(getClassProperties(Sample.class)); // {"type", "name", "value"}
}

【讨论】:

    猜你喜欢
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    相关资源
    最近更新 更多