Using Reflection to Count Methods.

I need 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 is sets and index 1 gets.

Can someone give me a high level approach to solving this problem?

+4
source share
3 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 quick reference on the API Reflection look here .

+10
source
 public static int[] countGettersandSetters(String c) throws ClassNotFoundException { int[] count = new int[2]; Class<?> classs = Class.forName(c); Field[] fields = classs.getDeclaredFields(); for (Field field : fields) { String name = field.getName(); try { classs.getMethod("set"+name.substring(0, 1).toUpperCase()+name.substring(1) , null); count[0]++; } catch (NoSuchMethodException e) { } try { classs.getMethod("get"+name.substring(0, 1).toUpperCase()+name.substring(1), field.getType()); count[1]++; } catch (NoSuchMethodException e) { } } return count; } 
+1
source

Given the standard naming convention, make sure there is a method with "get" or "set" with the class field name prefix:

 public static int[] count(Class<? extends Object> c) { int[] counts = new int[2]; Field[] fields = c.getDeclaredFields(); Method[] methods = c.getDeclaredMethods(); Set<String> fieldNames = new HashSet<String>(); List<String> methodNames = new ArrayList<String>(); for (Field f : fields){ fieldNames.add(f.getName().toLowerCase()); } for (Method m : methods){ methodNames.add(m.getName().toLowerCase()); } for (String name : methodNames){ if(name.startsWith("get") && fieldNames.contains(name.substring(3))){ counts[0]++; }else if(name.startsWith("set") && fieldNames.contains(name.substring(3))){ counts[1]++; } } return counts; } 

If you want to get all inherited getters / setters, replace getDeclaredFields() and getDeclaredMethods() with getFields() and getMethods() .

0
source

Source: https://habr.com/ru/post/1495248/


All Articles