lundi 2 mars 2020

Force Uniform Constructor and Method Annotation Values?

I'm writing a custom API using Reflection to save Objects to file. I have the following class structure:

@Constructor
public XYZPOJO(@Key(key = "word") String word, @Key(key = "variations") ArrayList<String> varList) {
    this.word = word;
    this.varList = varList;
}


String word;
ArrayList<String> varList = new ArrayList<String>();


@Key(key = "word")
public String getWord() {
    return word;
}

@Key(key = "variations")
public ArrayList<String> getVarList() {
    return varList;
}

When saving Object to file, my program retrieves each method annotated with @Key, invokes method and saves invoked value to file using the value of @Key as the property name. Later, when I want to construct instance of Object it will search for constructor annotated with @Constructor and then retrieve value of @Key of each parameter in constructor and retrieve value of key (property) from file.

My main issue is that for every field I want to persist I need to duplicate the @Key annotation (and value) before each method and before the corresponding parameter in constructor. Moreover, if both the constructor/method annotation do not match exactly it will fail to instantiate Object. It is very easy to accidentally copy the wrong values.

Is there a way to define each @Key just once?

I was thinking of adding @Key just once before each field I wish to persist however I believe (please correct me if I'm wrong) that I would no longer be able to instantiate class via constructor (I believe I would need to instantiate class by directly setting value of each field via reflection, thereby circumventing constructor, correct?). However, this is not ideal since the constructor performs certain necessary functions before the class is instantiated.

What other solution(s) are there?

Thanks!





Aucun commentaire:

Enregistrer un commentaire