Reflections in Java

With reflections, we can get the information about any class’s structure like its methods, fields, constructors etc. We can also create the instances of the classes at run time and invoke its methods. For example – Let us say we have a Student class in Java and we want to find all method and fields of that class.
 
package reflections;

/**
 * Created by ssalunke on 13/04/2016.
 */
public class Student {

    private int rollno;
    private String name;
    public int marks;

    public Student(int rn, String name, int marks) {
        this.rollno = rn;
        this.name = name;
        this.marks = marks;
    }

    public Student (int rn, String name){
        this.rollno = rn;
        this.name = name;
        this.marks = 0;
    }

    public Student (int rn){
        this.rollno = rn;
        this.name = "";
        this.marks = 0;
    }

    public int getMarks() {
        return marks;
    }

    public int getRollno() {
        return rollno;
    }


    public String getName() {
        return name;
    }

    public void setMarks(int marks) {
        this.marks = marks;
    }

    public void setName(String name) {
        this.name = name;
    }

}
Finding field information of Student class

package reflections;

import org.junit.Test;

import java.lang.reflect.Field;

/**
 * Created by ssalunke on 13/04/2016.
 */
public class TestFields {

    @Test
    public void testField() throws Exception{
        Class studentClass = Student.class;

        Student s1 = new Student(11,"Sagar");

        // gets all the public member fields of the class Student
        Field[] fields = studentClass.getFields();

        System.out.println("Public Fields are: ");
        for (Field oneField : fields) {
            // get public field name
            Field field = studentClass.getField(oneField.getName());
            String fieldname = field.getName();
            System.out.println("Fieldname is: " + fieldname);

            // get public field type
            Object fieldType = field.getType();
            System.out.println("Type of field " + fieldname + " is: "
                    + fieldType);

            // get public field value
            Object value = field.get(s1);
            System.out.println("Value of field " + fieldname + " is: "
                    + value);

        }

        // How to access private member fields of the class

        // getDeclaredField() returns the private field
        Field privateField = Student.class.getDeclaredField("name");

        String name = privateField.getName();
        System.out.println("One private Fieldname is: " + name);
        // makes this private field instance accessible
        // for reflection use only, not normal code
        privateField.setAccessible(true);

        // get the value of this private field
        String fieldValue = (String) privateField.get(s1);
        System.out.println("fieldValue = " + fieldValue);
    }
}
Here is the output of above example.

Public Fields are:
Fieldname is: marks
Type of field marks is: int
Value of field marks is: 0
One private Fieldname is: name
fieldValue = Sagar
Now let us try to find method information of Student class.

package reflections;

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

/**
 * Created by ssalunke on 13/04/2016.
 */
public class TestMethods {

    public static void main(String[] args) throws Exception {

        Class studentClass = Student.class;

            // get the name of the class including package name
            System.out.println("Class Name (including package) is -> " + studentClass.getName());

            // get the name of the class excluding package
            System.out.println("Class Name (excluding package) is -> " + studentClass.getSimpleName());

            System.out.println("Package Name of the class is -> " + studentClass.getPackage());

            // get all the constructors of the class
            Constructor[] constructors = studentClass.getConstructors();
            System.out.println("Constructors are: "
                    + Arrays.toString(constructors));

            // get constructor with specific argument
            Constructor constructor = studentClass.getConstructor(Integer.TYPE);

            // initializing an object of the RentCar class
            Student s1 = (Student) constructor.newInstance(111);

            // get all methods of the class including declared methods of superclasses
            Method[] allmethods = studentClass.getMethods();
            System.out.println("Methods are: " + Arrays.toString(allmethods));
            for (Method method : allmethods) {
                System.out.println("method = " + method.getName());
            }

            // get all methods declared in the class but excludes inherited methods.
            Method[] declaredMethods = studentClass.getDeclaredMethods();
            System.out.println("Declared Methods are: "
                    + Arrays.toString(declaredMethods));
            for (Method dmethod : declaredMethods) {
                System.out.println("method = " + dmethod.getName());
            }

            // get method with specific name and parameters
            Method oneMethod = studentClass.getMethod("setName",
                    new Class[]{String.class});

            System.out.println("Method is: " + oneMethod);

            oneMethod.invoke(s1, "Sagar");

            // get all the parameters of setName
            Class[] parameterTypes = oneMethod.getParameterTypes();
            System.out.println("Parameter types of setName are: "
                    + Arrays.toString(parameterTypes));

            // get the return type of setName
            Class returnType = oneMethod.getReturnType();
            System.out.println("Return type is: " + returnType);

    }
}

Class Name (including package) is -> reflections.Student
Class Name (excluding package) is -> Student
Package Name of the class is -> package reflections
Constructors are: [public reflections.Student(int), 
    public reflections.Student(int,java.lang.String), 
    public reflections.Student(int,java.lang.String,int)]
Methods are: [public java.lang.String reflections.Student.getName(), 
    public void reflections.Student.setName(java.lang.String),
     public int reflections.Student.getMarks(), 
     public int reflections.Student.getRollno(), 
     public void reflections.Student.setMarks(int), 
     public final void java.lang.Object.wait() throws java.lang.InterruptedException, 
     public final void java.lang.Object.wait(long,int)
      throws java.lang.InterruptedException, 
      public final native void java.lang.Object.wait(long) 
      throws java.lang.InterruptedException, 
      public boolean java.lang.Object.equals(java.lang.Object), 
      public java.lang.String java.lang.Object.toString(), 
      public native int java.lang.Object.hashCode(), 
      public final native java.lang.Class java.lang.Object.getClass(), 
      public final native void java.lang.Object.notify(), 
      public final native void java.lang.Object.notifyAll()]
method = getName
method = setName
method = getMarks
method = getRollno
method = setMarks
method = wait
method = wait
method = wait
method = equals
method = toString
method = hashCode
method = getClass
method = notify
method = notifyAll
Declared Methods are: [public java.lang.String reflections.Student.getName(), 
    public void reflections.Student.setName(java.lang.String), 
    public int reflections.Student.getMarks(), public int reflections.Student.getRollno(),
     public void reflections.Student.setMarks(int)]
method = getName
method = setName
method = getMarks
method = getRollno
method = setMarks
Method is: public void reflections.Student.setName(java.lang.String)
Parameter types of setName are: [class java.lang.String]
Return type is: void

Web development and Automation testing

solutions delivered!!