mardi 6 janvier 2015

Find references to method invocations in java to clean up unused pojo fields using reflection

I have a fat pojo java class with a huge amount of fields / getters & setters. Some of those fields are no longer being used and I'd like to clean-up that class. I don't know much about reflection but I would like to be able to programatically identify fields that are no longer being referenced in another class.


The way to identify if a field needs to be cleaned up is to see if the field's setter method is being invoked in another, if not, its a candidate for clean-up.


I got as far as figuring out how to extract methods and field names using reflection, but I don't know where to begin identifying those fields whos setters are not referenced in another class's execution.


public class GetterSetterReflec {



public static void main(String args[]){
printGettersSetters(SearchEngineClientModel.class);
}

public static void printGettersSetters(Class<?> aClass)
{
Method[] methods = aClass.getMethods();

Field[] fields = aClass.getDeclaredFields();
for(Field field : fields){
System.out.println(field);
}

for(Method method : methods){
if(isGetter(method)) System.out.println("getter: " + method);
if(isSetter(method)) System.out.println("setter: " + method);
}
}

public static boolean isGetter(Method method){
if(!method.getName().startsWith("get")) return false;
if(method.getParameterTypes().length != 0) return false;
if(void.class.equals(method.getReturnType()))
return false;
return true;
}

public static boolean isSetter(Method method){
if(!method.getName().startsWith("set")) return false;
if(method.getParameterTypes().length != 1) return false;
return true;
}


}


I'd be grateful for any help you can provide. Thank you in advance!






Aucun commentaire:

Enregistrer un commentaire