 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Call methods of an object using reflection in Java
The methods of an object can be called using the java.lang.Class.getDeclaredMethods() method. This method returns an array that contains all the Method objects with public, private, protected and default access. However, the inherited methods are not included.
Also, the getDeclaredMethods() method returns a zero length array if the class or interface has no methods or if a primitive type, array class or void is represented in the Class object.
A program that demonstrates this is given as follows −
Example
import java.lang.reflect.Method; class ClassA {    private String name = "John";    public String returnName() {       return name;    } } public class Demo {    public static void main(String[] args) throws Exception {       Class c = ClassA.class;       Method[] methods = c.getDeclaredMethods();       ClassA obj = new ClassA();       for (Method m : methods) {          Object result = m.invoke(obj, new Object[0]);          System.out.println(m.getName() + ": " + result);       }    } }  Output
returnName: John
Advertisements
 