Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform java class fields to an array of string values

Tags:

java

arrays

I am looking for a clean and elegant way to transform an object variables into an array based on the variable values.

Example:

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;

}

Based on the values of each field, I want to add the field name as a string into an array.

Example: new Subject(true, true, true, false, false)

Expected result: ["music", "food", "sport"]

like image 396
Jason Canto Avatar asked May 01 '19 21:05

Jason Canto


2 Answers

Assuming no getters, you can use reflection:

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


Working example

like image 63
Benjamin Urquhart Avatar answered Oct 03 '22 20:10

Benjamin Urquhart


For a general solution you can use reflection and Java Streams for this:

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

The result will be:

[music, food, sport]
like image 31
Samuel Philipp Avatar answered Oct 03 '22 19:10

Samuel Philipp