【问题标题】:Java: Using reflection to fill all the setters from a classJava:使用反射填充类中的所有设置器
【发布时间】:2017-06-16 19:35:01
【问题描述】:

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

目前我这样做了:

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

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

【问题讨论】:

    标签: java reflection no-framework


    【解决方案1】:

    不能填充设置器,因为它们是方法(功能),而不是值本身。但是...
    可以填写与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 中执行您需要的任何操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 2017-11-07
      相关资源
      最近更新 更多