Java: using reflection to populate all setters from a class

I have an X class with maybe 100 String in it, and I want to make a function that mimics an object of this class for all setters that starts with "setTop".

At the moment, I have done this:

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

And I don’t know how to do it now, and I’m not sure that I can fill all these setters. In my environment, I cannot use Frameworks, and I am in Java 6. I have not found this exact question in stackoverflow before. Can someone help me with this please?

Thank.

+4
source share
1 answer

, (), . ...
CAN () , .


, :

class Example {
    String name;

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

:

  • (getTopXXX topXXX)

:

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.

+2

Source: https://habr.com/ru/post/1668381/


All Articles