Reflection in java

  • Reflection is used to analyse a class at runtime.
  • It is used to get the structure of a class at run time.
  • Through reflection we are able to retrieve the information like constructors, fields and methods associated with the class.
  • Reflection is used to change the values of data fields in objects.

    For example consider the class 'Person'

    package com.java;

    public class Person {
    private String name;
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public int getAge() {
    return age;
    }
    public void setAge(int age) {
    this.age = age;
    }
    private int age;

    }

    Reflection class

    package com.java;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    public class ReflectionExample {

    public static void main(String[] args) {
    try {
    // Creates an object of type Class which contains the information of
    // the class String
    Class cl = Class.forName("com.java.Person");

    // getDeclaredFields() returns all the constructors of the class.
    Constructor cnst[] = cl.getConstructors();

    // getFields() returns all the declared fields of the class.
    Field fld[] = cl.getDeclaredFields();

    // getMethods() returns all the declared methods of the class.
    Method mtd[] = cl.getMethods();
    System.out.println("Name of the Constructors of the String class");

    for (int i = 0; i < cnst.length; i++) {
    System.out.println(cnst[i].getName().toString());
    }

    System.out.println("Name of the Declared fields");

    for (int i = 0; i < fld.length; i++) {
    System.out.println(fld[i].getName().toString());
    }

    System.out.println("Name of the Methods");

    for (int i = 0; i < mtd.length; i++) {
    System.out.println(mtd[i].getName().toString());
    }

    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    }
    }

    }

    Result
    Name of the Constructors of the String class
    com.java.Person
    Name of the Declared fields
    name
    age
    Name of the Methods
    getAge
    setAge
    getName
    setName
    wait
    wait
    wait
    hashCode
    getClass
    equals
    toString
    notify
    notifyAll

No comments:

 Python Basics How to check the version of Python interpreter mac terminal

Popular in last 30 days