How to get object's fields as comma separated string or a list in java

Viewed 472

I am trying to get the object's properties as a list. So for example:

class Sample {

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

Expected output: {"type", "name", "value"}

Is there a programmatical way to do this?

1 Answers

You can use Java Reflexion

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

Usage example:

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