Monday, July 17, 2017

Reflection in java

Reflection API

        1)      Package- java.lang.reflect 
        2)      Through reflection we can invoke methods at runtime irrespective of the access specifier              used with them.



Student.java

We’ll be creating Methods, Object, Constructor and call methods of below class using Reflection API

package com.reflection;

class Student {

     public int rollnum;
     public String name;
    
     /*Default constructor */
     public Student() {
          System.out.println("No-args Constructor");
     }
     /*Parameterized constructor */
     public Student(int rollnum, String name) {
          this.rollnum = rollnum;
          this.name = name;
     }

     // Creating a public method with no arguments
     public void method1() {
          System.out.println("The string is " + name +
                   "RollNum is "+ rollnum);
     }

     // Creating a public method with int as argument
     public void method2(int n) {
          System.out.println("The number is " + n);
     }

     // creating a private method
     private void method3() {
          System.out.println("Private method invoked");
     }
}

Below class will be using Reflection API to create member variable of above class.

package com.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestReflection {
    
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException, InstantiationException {
         
       /* Creating object whose property is to be checked */
        Student student = new Student();
         
        /*Creating class object using getClass method*/
        Class clas = student.getClass();
        System.out.println("Name of class is"+clas.getName());
       
        /* Getting the constructor of the class
        through the object of the class*/
       
        System.out.println("Finding number of constructors in a class");
        Constructor constructor[]=clas.getConstructors();       
        for(Constructor con : constructor)
        System.out.println(con.getName());
       
        System.out.println("Finding number of methods in a class");
        /*Find methods*/
        Method methods[] = clas.getMethods();
        for(Method method : methods)
          System.out.println(method.getName());
       
        /*Create object of method class passing MethodName and          parameter types*/
        Method method = clas.getDeclaredMethod("method2",int.class);
        /*Invoking a method at run time*/
        method.invoke(student,10);
       
        /*Getting fields at run time .It gives only public              fields of the class*/
        Field fields[] = clas.getFields();
        for(Field field : fields)
          System.out.println(field);
       
        /* Setting fields of an object*/
        Field field_rollnum =clas.getDeclaredField("rollnum");
        field_rollnum.setAccessible(true);
        field_rollnum.set(student, 100);
       
        Field field_name=clas.getDeclaredField("name");
        field_name.setAccessible(true);
        field_name.set(student, "Paras");
       
   /*Calling method and getting values of field which we set*/
        Method method_field = clas.getDeclaredMethod("method1");
        method_field.invoke(student);
       
        /*Invoking no-args constructor of an class and                 creating a new instance at run time*/
        Constructor noArgConst = clas.getConstructor();
        Student student1= (Student) noArgConst.newInstance();
        student1.method1();
       
        /*Invoking parameterized constructor of a class*/
        Constructor paramConst = clas.getConstructor(int.class,String.class);
        System.out.println("Parameterized constructor"+ paramConst);
       
        Student student2= (Student) paramConst.newInstance(1055,"Paras");
        student2.method1();
     }   
}

Output

No-args Constructor
Name of class iscom.reflection.Student
Finding number of constructors in a class
com.reflection.Student
com.reflection.Student
Finding number of methods in a class
method2
method1
wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll
The number is 10
public int com.reflection.Student.rollnum
public java.lang.String com.reflection.Student.name
The string is ParasRollNum is 100
No-args Constructor
The string is nullRollNum is 0
Parameterized constructorpublic com.reflection.Student(int,java.lang.String)
The string is ParasRollNum is 1055


No comments:

Post a Comment