Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Reflection to Count Methods.

Tags:

java

I have to write a function

public static int[] countGettersandSetters (String classname)

to count the number of get and set methods and return as an array where index 0 are sets and index 1 are gets.

Can anyone give me a high level approach to how to solve this problem?

like image 715
duckduck Avatar asked Dec 21 '22 02:12

duckduck


1 Answers

public static int[] countGettersandSetters (String className)
    int[] count = new int[2];
    Method[] methods = Class.forName(className).getDeclaredMethods();
    for (Method method : methods) {
        if (method.getName().startsWith("set")) {
            count[0]++;
        } else if (method.getName().startsWith("get") ||
                   method.getName().startsWith("is")) { // to incl. boolean properties
            count[1]++;
        } 
    }
    return count;
}

For a concise tutorial on Reflection API take a look here.

like image 65
Ravi K Thapliyal Avatar answered Jan 08 '23 08:01

Ravi K Thapliyal