I am using Gson to serialize my objects, but I ran into an issue which is that you can't read abstract objects after I have successfully saved them. I found this which pertains to my question, but it differs in a few keyways. Mainly, I am saving an object that contains a map where the maps value holds a reference to an abstract class. If this issue did not exist my code would look very clean here is a minimized version of how everything looks right now.
private void recoverData() {
final File file = new File(this.getDataFolder(), "data.json");
if(file.exists() && file.length() > 2) {
try {
final Gson gson = new GsonBuilder().setPrettyPrinting().create();
final Type type = new TypeToken<Map<String, DataObj>>() {}.getType();
DataObj.DATA = gson.fromJson(new FileReader(file), type);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class DataObj implements Comparable<DataObj> {
public static transient Map<String, DataObj> DATA = new HashMap<>();
// This also contains 20+ more fields (but those all serialize fine)
public final Map<Upgrades, PlayerUpgrades> upgradesMap = new HashMap<>();
}
public abstract class PlayerUpgrades implements Serializable {
public int level;
public abstract String upgradeName();
public abstract Integer maxLevel();
}
I then have many "PlayerUpgrades" that extends PlayerUpgrades
but I am not sure how to correctly get my upgradesMap to serialize. Does there happen to be a way I can denote something inside of PlayerUpgrades
so I can manually create new instances of each class depending on the key from the upgradesMap? I bet I could try and manually serialize everything in my DataObj but since I have tons of fields, I feel like that would take a while and look clunky so how should I approach this?