4

我必须写一个函数

public static int[] countGettersandSetters (String classname)

计算 get 和 set 方法的数量并作为数组返回,其中索引 0 是集合,索引 1 是获取。

谁能给我一个高级方法来解决这个问题?

4

3 回答 3

10
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;
}

有关反射 API 的简明教程,请查看此处

于 2013-08-05T03:24:46.603 回答
1
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;
}
于 2013-08-05T03:52:25.753 回答
0

考虑标准命名约定,检查是否存在以“get”或“set”为前缀的类字段名称的方法:

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;
}

如果您还想获取所有继承的 getter/setter,请将getDeclaredFields()andgetDeclaredMethods()替换为getFields()and getMethods()

于 2013-08-05T03:33:24.637 回答