Java Reflection API


– Java Reflection process is used to examine or modifying the behaviour of a class at run time.
– Main class of which is used in reflection is java.lang.Class.
– It provides methods like static method forName(), getClass(), and using .class syntex of the class.

Using Class.forName():

Class AnyClass { }

Class Demo {
main(String[] args){
Class c = Class.forName(“AnyClass”);
S.o.p(c.getClass());
}
}


Output: AnyClass

Using getClass() method:

Class AnyClass { }
Class Demo {
      Void show(Object obj){
         Class c = obj.getClass();
         S.O.P(c.getName());
      }
      main(String[] args){
         AnyClass anyClass = new AnyClass();
         Demo demo = new Demo();
         demo.show(anyClass);
      }
}


Output: AnyClass

Using .class syntax:

Class Demo {
   main(String[] args){
     Class c  = boolean.class;
     S.o.p(c.getClass());
   }
}


Output: boolean