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?
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With