mardi 5 juillet 2016

Java self-reflection

It's rather strange, but I want to call self method.

This is my abstract class

public abstract class AbstractMapper {
    public AbstractMapper(Map<String, String> map) {
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field: fields) {
            if (field.getAnnotation(Column.class) != null) {
                String fName = field.getName();
                String rsName = field.getAnnotation(Column.class).name();
                StringBuilder sb = new StringBuilder("set")
                        .append(Character.toUpperCase(fName.charAt(0)))
                        .append(fName.substring(1));
                String mName = sb.toString();

//              this.invoke(mName, map.get(fName)); <-- What should I put this here?
            }
        }
    }
    public Result getCalculatedValues() {
        return xxxx;
    }
}

And this is my class

public class NewMachine extends AbstractMapper{
    @column(name = machine)
    private String machine;

    @column(name = temperature)
    private Double temperature;

    // normal get/set methods

 }

Now, my goal is that AbstractMapper constructor iterates through all fields with columns, and invoke all of its respective setters.

in this case, I can pass something like

Map<String, String> map = SomeClass.SomeMethod();
NewMachine m = new NewMachine(map);
Result r = m.getCalculatedValues();

Thank you for helping.





Aucun commentaire:

Enregistrer un commentaire