Java 使用反射计算方法。
我必须写一个函数Java 使用反射计算方法。,java,Java,我必须写一个函数 public static int[] countGettersandSetters (String classname) 计算get和set方法的数量,并作为数组返回,其中索引0为set,索引1为get 谁能给我一个高层次的方法来解决这个问题 public static int[] countGettersandSetters (String className) int[] count = new int[2]; Method[] methods = Cl
public static int[] countGettersandSetters (String classname)
计算get和set方法的数量,并作为数组返回,其中索引0为set,索引1为get
谁能给我一个高层次的方法来解决这个问题
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的简明教程,请查看。考虑到标准命名约定,请检查是否存在在类的字段名称前加有“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;
}
publicstaticint[]count(类publicstaticint[]countGettersandSetters(字符串c)抛出ClassNotFoundException{
int[]计数=新的int[2];
Class classs=Class.forName(c);
Field[]fields=classs.getDeclaredFields();
用于(字段:字段){
字符串名称=field.getName();
试一试{
getMethod(“set”+name.substring(0,1).toUpperCase()+name.substring(1),null);
计数[0]++;
}捕获(无此方法例外){
}
试一试{
getMethod(“get”+name.substring(0,1).toUpperCase()+name.substring(1),field.getType());
计数[1]++;
}捕获(无此方法例外){
}
}
返回计数;
}
<代码> >使用java反射——您是否必须考虑<代码> <代码> > BooLoe<代码> >?我可能错了,还没有测试它,但是我相信这只会返回当前类的方法,而不是它父类声明的任何方法…@ MaldCuoter,这是正确的。<代码>不包括继承的方法。@下位者的想法是将OP推到正确的方向。不要搅动生产类代码。SETER必须有1个参数,而吸气剂不应该有任何参数。并且您的答案没有考虑。@ J.HASH,请注意,这里没有调用这些方法。因此,有多少个参数?它们采取的是无关紧要的。而且,这里检查字段名的其他答案也不正确,因为JavaBean属性不要求底层字段名与其getter/setter匹配。JavaBean属性不要求底层字段名与其getter/setter匹配。因此,检查是不必要的,并且可能会y报告的属性方法数量不正确。JavaBean属性不需要底层字段名来匹配其getter/setter。因此,检查是不必要的,并且可能报告的属性方法数量不正确。
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;
}