Suresh Raja
Suresh Raja

Reputation: 421

How to find the access modifier of a member using java reflection

Find the access modifier of a member using java reflection

private final static long serialId = 1L;
protected String title;
public String FirstName;

I need to know which variable is private, protected and public?

Upvotes: 3

Views: 6099

Answers (2)

Andrew
Andrew

Reputation: 690

For all fields in the class (assuming class is named theClass)

Field[] fields = theClass.getDeclaredFields();
for (Field field : fields) {
    int modifers = field.getModifiers();
    if (Modifier.isPrivate(modifers)) {
        System.out.println(field.getName() + " is Private");
    }
}

The following methods determine could also be used:

boolean isPrivate(Field field){
    int modifers = field.getModifiers();
    return Modifier.isPrivate(modifers);
}

boolean isProtected(Field field){
    int modifers = field.getModifiers();
    return Modifier.isPublic(modifers);
}

boolean isPublic(Field field){
    int modifers = field.getModifiers();
    return Modifier.isProtected(modifers);
}

Example usage (given a class called theClass)

Field titleField = theClass.getField("title");
boolean titleIsProtected = isProtected(titleField);

Upvotes: 3

If you have a class (in the code below Vlucht ) then you can use the method getDeclaredFields()... then every field instance can invoke the method getModifiers which are explainted in the table below..

Reflection API has been the same since jdk1.5 so java8 is not relevant for reflection but more for accessing the array of fields using streams or similar..

if you really need something Human readable like :

private static final

protected or public

then use System.out.println(Modifier.toString(mod));

System.out.println(Modifier.toString(mod));

public class Vlucht {
    private final static long serialId = 1L;
    protected String title;
    public String FirstName;

    public static void main(String[] args) {
    Field[] reflectedClass = Vlucht.class.getDeclaredFields();
    for (Field field : reflectedClass) {
        int mod = field.getModifiers();
        System.out.println(mod);
    }
    }
}

enter image description here

Upvotes: 6

Related Questions