Way2Java

Get Access Specifiers and Modifiers of a Class

It is advised to read the notes on Java Reflection API before attempting the programs.

Example to get Access Specifiers and modifiers of a class.
import java.awt.Button;
import java.lang.reflect.Modifier;
public final class Demo
{
  public static void main(String [] args) 
  {
    Demo d1 = new Demo();
    System.out.println("Object d1 belongs to " + d1.getClass());    // prints class Demo

// infact, the above statment can be split as follows 

    Class c = d1.getClass();                                             // Class is from java.lang package
    System.out.println("Object d1 belongs to " + c);    // prints class Demo
    System.out.println("Object d1 belongs to " + c.getName());    // prints Demo

    Button btn = new Button("OK");
    Class c1 = btn.getClass();
    System.out.println("Object btn belongs to " + c1.getName());    // prints java.awt.Button  

// Class c is the starting point to get all the info of Demo class

// to get the access specifier and modifier of class Demo

    int m = c.getModifiers();
    if(Modifier.isPublic(m))    // Modifier class is from reflect package
      System.out.println("public");  	       // prints public
    if(Modifier.isProtected(m))
      System.out.println("protected");
    if(Modifier.isPrivate(m))
      System.out.println("private");
    if(Modifier.isFinal(m))
      System.out.println("final");  // prints final
  }
}