3

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
  • 2
    Try referencing link. Commented May 28, 2021 at 15:31

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.