Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 644
Atihska Avatar asked Dec 20 '25 20:12

Atihska


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

Output:

{"type", "name", "value"}

like image 77
Ahmed HENTETI Avatar answered Dec 23 '25 12:12

Ahmed HENTETI



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!