Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to determine class modifiers dynamically using Java Reflection API ?.

Program to demonstrate how to determine class modifiers dynamically using Java Reflection API

package com.hubberspot.reflection;

import java.lang.reflect.Modifier;

// Create classes with different modifiers as
// final, abstract, public etc
abstract class Animal
{

}

public final class Dog extends Animal {

 public static void main(String[] args) {

  System.out.println("---------------------------------------------");

  // Get the instance of Class as Dog.class
  Class classDog = Dog.class;

  // Class class has a method called as  getModifiers(). 
  // This method Returns the Java language modifiers for 
  // the class as a integer. The modifiers consist of the 
  // Java Virtual Machine's constants for public, protected, 
  // private, final, static, abstract and interface; 
  // they should be decoded using the methods of class Modifier.  
  int modifier = classDog.getModifiers();

  // Modifier class has many static methods such as isPublic , 
  // isPrivate, isStatic, isFinal, isAbstract etc. These methods
  // returns back a boolean value checking whether given argument to 
  // method is of particular modifier
  // See below for the demo ... 
  if(Modifier.isPublic(modifier))
  {
   System.out.println("Class Dog is declared as:  public");
  }

  if(Modifier.isFinal(modifier))
  {
   System.out.println("Class Dog is declared as:  final");
  }

  if(!Modifier.isStatic(modifier))
  {
   System.out.println("Class Dog is not declared as:  static");
  }

  System.out.println("---------------------------------------------");

  Class classAnimal = Animal.class;

  modifier = classAnimal.getModifiers();

  if(Modifier.isAbstract(modifier))
  {
   System.out.println("Class Animal is declared as:  abstract");
  }

  if(!Modifier.isFinal(modifier))
  {
   System.out.println("Class Animal is not declared as:  final");
  }

  if(!Modifier.isStatic(modifier))
  {
   System.out.println("Class Animal is not declared as:  static");
  }

  System.out.println("---------------------------------------------");
 }
}





Output of the program :



 
© 2021 Learn Java by Examples Template by Hubberspot