Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting Getters and Setters [closed]

Tags:

java

I am working on a project that requires to count the number of getters and setters in a compiled java code. I am new to this and dont know where and how to start. I have installed eclipse and added the Bytecode plugin to see the bytecode of the java code.

Any thoughts on what i need to do next?

like image 577
user2214408 Avatar asked Jan 24 '14 04:01

user2214408


2 Answers

You can use java.lang.reflect.* package to get all the class info such as variable, methods, constructors and inner classes.

Example:

public int noOfGettersOf(Class clazz) {
    int noOfGetters = 0;
    Method[] methods = clazz.getDeclaredMethods()
    for(Method method : methods) {
        String methodName = method.getName();
        if(methodName.startsWith("get") || methodName.startsWith("is")) {
            noOfGetters++;
        }
    }
    return noOfGetters;
}

Follow the same approach for setters, one thing you need to consider is boolean getters they usually starts with is instead of get.

like image 99
RP- Avatar answered Oct 04 '22 20:10

RP-


You can use Class.getDeclaredMethods(), with something like this

public static int countGets(Class<?> cls) {
  int c = 0;
  for (java.lang.reflect.Method m : cls.getMethods()) {
    if (m.getName().startsWith("get")) {
      c++;
    }
  }
  return c;
}

public static int countSets(Class<?> cls) {
  int c = 0;
  for (java.lang.reflect.Method m : cls.getMethods()) {
    if (m.getName().startsWith("set")) {
      c++;
    }
  }
  return c;
}
like image 40
Elliott Frisch Avatar answered Oct 04 '22 21:10

Elliott Frisch