I have a struct that doesn't enforce any invariants, (i.e. it exists to carry data for other classes), so its fields are public and it has no (declared) constructor:
public class Observation {
public short truncatedSeed;
public final int[] levels = { 0, 0, 0 };
public final int[] stride1 = { -1, -1, -1 };
public final int[] stride2 = { -1, -1, -1 };
public int power = -2;
public long now = -1; // Not used in equals()/hashCode()
@Nullable public Item item;
}
If I want to create a static final
instance of this, how do I do that? Have newer Javas finally introduced good syntax for handling this case? The best I've been able to come up with is:
public static final EMPTY = new Observation() {
{
truncatedSeed = (short) 0xDEAD;
item = Item.EMPTY;
}
};
...which does work, but creates an anonymous subclass, which seems... icky.
Edit: Since Java's final is shallow, none of the members here will be immutable. Given that, the most straightforward approach is probably to embrace this fact:
public static EMPTY = new Observation();
static {
truncatedSeed = (short) 0xDEAD;
item = Item.EMPTY;
}