Display various methods and Field in a class using Reflection in Java


Reflection (java.lang.reflect) is mainly used to get entire information about the class and their related information declared in a class can be obtained .Here i have explained a sample program to demonstrate how the reflection will work.
// Comment


import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.util.Date;

/**
 *
 * @author allinalljava.blogspot.com
 */
public class samplereflect {
    
    /**
     * List various methods in a class using Reflection in Java .
     */
    public void listMethodsUsingReflection() {

        //Obtain the Class instance
        Class employeeClass = Employee.class;
        
        //Get the Declared methods in employeeClass
        Method[] methodsList = employeeClass.getDeclaredMethods();
        System.out.println("This are the methods that have been declared in Employee Class");
        //Loop through the methodsLists and print out their names
        for (Method methodInstance : methodsList) {
            System.out.println(methodInstance.getName());
        }
        //Get the Declared FieldLists in employeeClass
        Field[] fieldList = employeeClass.getDeclaredFields();
        //Loop through the fieldLists and print out their names
        System.out.println("This are the Fields that have been declared in Employee Class");
        for (Field fieldInstance : fieldList) {
            System.out.println(fieldInstance.getName());
        }
        
    }
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new samplereflect().listMethodsUsingReflection();
    }
    
    
    class Employee {
        
        private String empName;
        private String empAddress;
        private String empAge;
        private Date empDob;
        
  public void setEmpName(String empName) {
   this.empName = empName;
  }
  public String getEmpName() {
   return empName;
  }
  public void setEmpAddress(String empAddress) {
   this.empAddress = empAddress;
  }
  public String getEmpAddress() {
   return empAddress;
  }
  public void setEmpAge(String empAge) {
   this.empAge = empAge;
  }
  public String getEmpAge() {
   return empAge;
  }
  public void setEmpDob(Date empDob) {
   this.empDob = empDob;
  }
  public Date getEmpDob() {
   return empDob;
  }

    
    }
}
Output
This are the methods that have been declared in Employee Class
setEmpName
getEmpName
setEmpAddress
getEmpAddress
setEmpAge
getEmpAge
setEmpDob
getEmpDob
This are the Fields that have been declared in Employee Class
empName
empAddress
empAge
empDob
raja P Web Developer

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...