我必须写一个函数
public static int[] countGettersandSetters (String classname)
计算get和set方法的数量,并返回索引0为集合且索引为1的数组。
有人能给我一个如何解决这个问题的高级方法吗?
答案 0 :(得分: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;
}
有关Reflection API的简明教程,请查看here。
答案 1 :(得分: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;
}
答案 2 :(得分: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()
和getDeclaredMethods()
替换为getFields()
和getMethods()
。