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
      System.out.println("final");  // prints final

2 thoughts on “Get Access Specifiers and Modifiers of a Class”

    1. In Java, modifiers and access modifiers are both one and the same. Access modifiers modifies the access (where as specifiers specifies the access). Generally access specifiers works between the classes of different packages where as modifiers works within one program also. For example, if a method is static (in the same class even), the method can be called without the help of an object (it is the modification, else, the method should be called with an object).

Leave a Comment

Your email address will not be published.