I have two enums that cross reference each other. Each one has a constructor that has a parameter for other enum.
They look something like:
SchoolEnum(ImmuneEnum value)
{
   this.immune = value;
}
ImmuneEnum(SchoolEnum value)
{
   this.school = value;
}
However depending on which Enum I call first, I can get a null value for the reference variable.
ImmunityEnum immune = ImmunityEnum.IMMUNE_KANNIC; 
SchoolEnum school = SchoolEnum.KANNIC;
System.out.println(school.getImmune())
System.out.println(immune.getSchool());
Produces the output: null Kannic
SchoolEnum school = SchoolEnum.KANNIC;
ImmunityEnum immune = ImmunityEnum.IMMUNE_KANNIC; 
System.out.println(school.getImmune())
System.out.println(immune.getSchool());
Produces the output: immunekannic null
It seems to be a bit of the "chicken and egg" problem as to when the enum is instantiated. But is there a way to have each one properly reference the other? I am considering making two singleton hashmaps that artificially cross reference the two, but is there a better idea?
It's not the prettiest solution in the world, but how about setting the cross-references afterwards?:
enum SchoolEnum {
    KANNIC;
    private ImmunityEnum immune;
    public ImmunityEnum getImmune() {
        return immune;
    }
    public void setImmune(ImmunityEnum immune) {
        this.immune = immune;
    }
}
enum ImmunityEnum {
    IMMUNE_KANNIC;
    private SchoolEnum school;
    public SchoolEnum getSchool() {
        return school;
    }
    public void setSchool(SchoolEnum school) {
        this.school = school;
    }
}
Now use it like this:
SchoolEnum school = SchoolEnum.KANNIC;
school.setImmune(ImmunityEnum.IMMUNE_KANNIC);
ImmunityEnum immune = ImmunityEnum.IMMUNE_KANNIC; 
immune.setSchool(SchoolEnum.KANNIC);
System.out.println(school.getImmune());
System.out.println(immune.getSchool());
What if you passing String parameters into your constructors:
public enum SchoolEnum {
   Kannic("immnunekannic");
   private String immune;
   public SchoolEnum (String immune) {this.immune = immune;}
   public ImmuneEnum getImmune() {
       return ImmuneEnum.valueOf(immune);
   }
}
public enum ImmnueEnum {
   immunekannic("Kannic");
   private String scholl;
   public ImmnueEnum (String school) {this.school = school;}
   public SchoolEnum getSchool() {
       return SchoolEnum.valueOf(school);
   }
}
But honestly it's a bit strange to create this type of domain model. What's your use case?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With