162. Getting public and private fields

The solution to this problem relies on the Modifier.isPublic() and Modifier.isPrivate() methods.

Let's assume the following Melon class has two public fields and two private fields:

public class Melon {

private String type;
private int weight;

public Peeler peeler;
public Juicer juicer;
...
}

First, we need to fetch the Field[] array corresponding to this class via the getDeclaredFields() method:

Class<Melon> clazz = Melon.class;
Field[] fields = clazz.getDeclaredFields();

Field[] contains all the four fields from earlier. Further, let's iterate this array and let's apply Modifier.isPublic() and Modifier.isPrivate() flag methods to each Field:

List<Field> publicFields = new ArrayList<>();
List<Field> privateFields = new ArrayList<>();

for (Field field: fields) {
if (Modifier.isPublic(field.getModifiers())) {
publicFields.add(field);
}

if (Modifier.isPrivate(field.getModifiers())) {
privateFields.add(field);
}
}

The publicFields list contains only public fields, and the privateFields list contains only private fields. If we quickly print these two lists via System.out.println(), then the output will be as follows:

Public fields:
[public modern.challenge.Peeler modern.challenge.Melon.peeler,
public modern.challenge.Juicer modern.challenge.Melon.juicer]

Private fields:
[private java.lang.String modern.challenge.Melon.type,
private int modern.challenge.Melon.weight]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset