Pages

How to get all Method information under a Class in Java Reflection?

This is continuing article of my previous post. In this article we will see how can we retrieve Class Related Information using Java Reflection .We will see Method Names .

Spatial Note : I will make a separate reflector utility class where we input a target class in its constructor and we will retrieve information using separate method. In this way ,we can isolate our needs. Please see this before start.How to get all declared Method Names inside of a class?This means , we will get the method names which are declared inside of the class(public , private, default, protected). Not inherited methods.

1:public String[] getAllOwnMethodNames(){

2: ArrayList<String> allMethods = new ArrayList<String>();

3:for(Method aMethod : myClass.getDeclaredMethods()){

4: allMethods.add("Method Name : "+aMethod.getName()+" , Full Name : "+aMethod.toString());

5: }

6:return allMethods.toArray(new String[allMethods.size()]);

7: }

How to get all Method Names accessible from of a class

(which includes inherited, implemented methods of its own, super class, interfaces)?
Thant means , we will get method names which are included in the class and the method which are taken from its parent class.

(include its parents and interfaces)

1:public String[] getAllPubliAndInheritedMethodNames(){

2: ArrayList<String> allMethods = new ArrayList<String>();

3:for(Method aMethod : myClass.getMethods()){

4: allMethods.add("Method Name : "+aMethod.getName()+" , Full Name : "+aMethod.toString());

5: }

6:return allMethods.toArray(new String[allMethods.size()]);

7: }

Note: To know information in detail i use getName() and toString() method especially.

For both case, we can specify method name to get that specific method.
myClass.getDeclaredMethod(<Name of the method as string>, parameter of that method)
myClass.getMethod(<Name of the method as string>, parameter of that method)

In the both case we need to know the name of the method.
In a class, often we need to know either the method is a Getter or a setter method.

We can apply small string filter. While iterating if we add like following

To know if it is a Getter method :

aMethod.getName().startsWith("set");

To know if it is a Setter method :

aMethod.getName().startsWith("get");

This is only class related method post, for method detail I will provide separate post. Thanks..:)