6

From this SO answer, I've gathered you can't access a private field without setting setAccessible(true). I could determine if a field is public or not with isAccessible(). However, how would I determine if it were public or private?

Lance Clark
  • 446
  • 7
  • 14
  • 1
    Check the [modifiers](https://docs.oracle.com/javase/tutorial/reflect/member/fieldModifiers.html). – shmosel Mar 13 '18 at 14:47

4 Answers4

16

You can use Field.getModifiers() to get the field modifiers. You can then use Modifier.is* to find out :

int modifiers = field.getModifiers();

if(Modifier.isProtected(modifiers)) {
  // protected
}
else if(Modifier.isPrivate(modifiers)) {
  // private 
}
Fathy
  • 4,939
  • 1
  • 23
  • 25
4

Given this class

class MyClass {
  public String v1;
  protected String v2;
  private String v3;
}

You can check the modifiers this way

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

Field field;
int modifier;

field = MyClass.class.getDeclaredField("v1");
modifier = field.getModifiers();
System.out.println(Modifier.toString(modifier));

field = MyClass.class.getDeclaredField("v2");
modifier = field.getModifiers();
System.out.println(Modifier.toString(modifier));

field = MyClass.class.getDeclaredField("v3");
modifier = field.getModifiers();
System.out.println(Modifier.toString(modifier));

Prints out:

public
protected
private
Bentaye
  • 9,403
  • 5
  • 32
  • 45
0

You got it wrong. You don't need reflection to access public fields. You can access them directly that's why they are public in the first place.

Besides that you can use getModifiers and parse that. See Retrieving and Parsing Field Modifiers

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
  • I think OP want to know if a random variable is public/protected/private using reflection, not access the value of that variable. Could be used to create a home made documentation ;) – AxelH Mar 13 '18 at 14:48
  • You're correct. I meant to put 'private' instead of 'public'. Fixed. – Lance Clark Mar 15 '18 at 19:26
0
public class Model {
    public int pub;
    private int priv;
}

and

public static void main(String[] args) {
        Field[] fields = Model.class.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            System.out.println(field.getName() + " : " + Modifier.toString(field.getModifiers()));
        }
    }
Jan Larsen
  • 831
  • 6
  • 13