How to Retrieve Object Method Names Using Java Reflection API

 Posted On  | Yashwant Chavan 

Java Reflection API provides great flexibility to retrieve the class metadata information , You can retrieve fields, method name,value using java Reflection.

Class.forName()

Returns the Class object associated with the class or interface with the given string name.

getDeclaredMethods()

Once You get the Class object instance using Class.forName() method. You can retrieve all the methods of that class using getDeclaredMethods(). In below example we are retrieve the Person pojo methods using reflection.

package com.technicalkeeda.app;

import java.lang.reflect.Method;

public class ReflectionTest {

    public static void main(String[] args) {
        try {
            Class c = Class.forName("com.technicalkeeda.bean.Person");
            Method method[] = c.getDeclaredMethods();
            for (int i = 0; i < method.length; i++)
                System.out.println("Method Names:- " + method[i].getName());
        } catch (Throwable e) {
            System.err.println(e);
        }
    }

}

Person Bean

Create simple Person bean class along with its getter setter methods.

package com.technicalkeeda.bean;

public class Person {

    private String firstName;
    private String lastName;
    private String email;

    public Person() {

    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

Output:)

Refer below Out put

Method Names:- getFirstName
Method Names:- setFirstName
Method Names:- getLastName
Method Names:- setLastName
Method Names:- getEmail
Method Names:- setEmail


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0360 seconds.