Java Reflection field get field modifiers

Introduction

We can apply modifiers (public, private, protected, transient, volatile, static and final) to a field.

The getModifiers() method returns an encoded integer representing the set of modifiers declared to the field.

The Modifier class has a set of methods to identify what modifiers the returned integer represent.

The following program lists all static fields of a given class:


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

public class Main {
   public static void main(String args[]) throws Exception {
      Class c = Class.forName("java.lang.String");
      Field[] fields = c.getDeclaredFields();
      System.out.println("Static fields:");
      for (Field f : fields)
         if (Modifier.isStatic(f.getModifiers()))
            System.out.println(f.getName());
   }//  ww w .  j a  v  a 2 s.co  m
}



PreviousNext

Related