javareflectionno-framework

Java: Using reflection to fill all the setters from a class


I have a class X with maybe 100 String in it and I want to do a function that mock an object of this class for all the setters which begins by "setTop".

For the moment I did 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 now and I'm not pretty sure I can fill all these setters like that. In my environment I can't use frameworks and I'm in Java 6.


Solution

  • You CANNOT fill the setters because they are methods (functionallities), not values itselfs. But...
    You CAN fill the value of the attributes (fields) of the class that corresponds to the getter.


    Imagine you have a class:

    class Example {
        String name;
    
        int topOne;
        int topTwo;
        int popTwo;  // POP!!!
        int topThree;
    }
    

    Taking:

    You can get only needed fields with reflection in this way:

    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()
                );
            }
        }
    }
    

    OUTPUT:

    int topOne
    int topTwo
    int topThree
    

    Now, do whatever you need inside the if (field.getName().startsWith("top")) { instead of a System.out.