Core Java

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

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

Note: I will make a separate reflector utility class where we input a target class in its constructor and we will retrieve information using a separate method. In this way, we can isolate our needs. Please see this before we start.

How to get all declared Method Names inside of a class?

This means, we will get the method names which are declared inside the class (public, private, default, protected), i.e. not inherited methods.

public String[] getAllOwnMethodNames(){

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

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

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

        }

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

    }

How to get all Method Names accessible from of a class (which includes inherited, implemented methods of its own, super class, interfaces)?

public String[] getAllPubliAndInheritedMethodNames(){

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

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

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

        }

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

    }

Note: To have the information in detail we use the getName() and toString() methods.

For both cases, we can specify the 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 both cases we need to know the name of the method. Sometimes, for a class, we need to know if a method is a Getter or a setter method. We can apply a small string filter, like the 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");
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Sergiuss
Sergiuss
9 years ago

To know if it is a Getter method :
Swap this:
To know if it is a Setter method :

Back to top button