Saturday 16 August 2014

Reflections

Reflections provides the facility to examine or modify the runtime behavior of applications running in the Java virtual machine. By using reflections you can inspect interfaces, classes, fields and methods at run time.

Example : To get all the declared method names.
public class Employee {
    String firstName, lastName;
    int id, age;
    
    String getFirstName(){
        return firstName;
    }
    
    String getLastName(){
        return lastName;
    }
    
    int getId(){
        return id;
    }
    
    int getAge(){
        return age;
    }
    
    void setFirstName(String firstName){
        this.firstName = firstName;
    }
    
    void setLastName(String lastName){
        this.lastName = lastName;
    }
    
    void setAge(int age){
        this.age = age;
    }
    
    void setId(int id){
        this.id = id;
    }
}

import java.lang.reflect.Method;

public class GetMethodNames {
    public static void main(String args[]){
        Method[] methNames = Employee.class.getDeclaredMethods();
        
        for(Method m : methNames){
            System.out.println(m.getName());
        }
    }
}

Output
getId
getAge
setAge
setId
getFirstName
getLastName
setFirstName
setLastName




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment