4

我有一个类 X,其中可能包含 100 个字符串,我想做一个函数,为所有以“setTop”开头的设置器模拟这个类的一个对象。

目前我这样做了:

public void setFtoMethods(Class aClass){
Methods[] methods = aClass.getMethods();
   for(Method method : methods){
      if(method.getName().startsWith("setTop")){
         method.invoke ....
      }
   }
}

而且我现在不知道该怎么做,我也不太确定我能不能像这样填补所有这些二传手。在我的环境中,我不能使用框架,而且我使用的是 Java 6。

4

1 回答 1

2

不能填充设置器,因为它们是方法(功能),而不是值本身。但是......
您可以填充对应于getter的类的属性(字段)的值


假设你有一个类:

class Example {
    String name;

    int topOne;
    int topTwo;
    int popTwo;  // POP!!!
    int topThree;
}

服用:

您可以通过这种方式仅通过反射获得所需的字段:

public static void main(String[] args) {
    inspect(Example.class);
}

public static <T> void inspect(Class<T> klazz) {
    Field[] fields = klazz.getDeclaredFields();
    for (Field field : fields) {
        if (field.getName().startsWith("top")) {
            // get ONLY fields starting with top
            System.out.printf("%s %s %s%n",
                    Modifier.toString(field.getModifiers()),
                    field.getType().getSimpleName(),
                    field.getName()
            );
        }
    }
}

输出:

int topOne
int topTwo
int topThree

现在,在里面做任何你需要的事情,if (field.getName().startsWith("top")) {而不是System.out.

于 2017-01-31T11:35:41.520 回答