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

后端 未结 2 394
萌比男神i
萌比男神i 2021-01-28 05:33

Find the access modifier of a member using java reflection

private final static long serialId = 1L;
protected String title;
public String FirstName;
相关标签:
2条回答
  • 2021-01-28 06:01

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

    0 讨论(0)
  • 2021-01-28 06:06

    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);
    
    0 讨论(0)
提交回复
热议问题