Saturday, 16 August 2014

Reflection - Methods

Reflection allows you to inspect methods and invoke them at run time.

Get All the declared methods in a class
You can get all the declared methods in a class using getDeclaredMethods() of Class object.

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.*;

public class GetDecllaredMethods {
    public static void main(String args[]) throws ClassNotFoundException{
        Class myClass = Class.forName("Employee");
        Method[] meth = myClass.getDeclaredMethods();
        
        System.out.println("Methods in Class Employee are");
        for(Method m : meth)
            System.out.println(m);
    }
}

Output
Methods in Class Employee are
int Employee.getId()
int Employee.getAge()
void Employee.setAge(int)
void Employee.setId(int)
java.lang.String Employee.getFirstName()
java.lang.String Employee.getLastName()
void Employee.setFirstName(java.lang.String)
void Employee.setLastName(java.lang.String)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment