All sorts of things happen when saving values to file: Sometimes you want to save a value representing an enum, and sometimes you want to save the real thing. And sometimes you have arrays of whatever that is... C# makes it easy: enums are the numbers that represent them, so an array of ints is practically an array of the enums you want – and vice-versa.
This doesn’t work well in Java – you can’t just cast the value to whatever you want it to be, you need to find a specific, existing, value. And, in order to do that, you need to know what value it is you’re looking for.
I had to do some work here with generics, so whatever you read from the hashtable is transformed into whatever it is you want. The DWIM (Do What I Mean) class helped me here.
Besides that, quite a lot of try-and-except work was done – nothing much intelligent. However, by this time a lot of the calls to getValueFromHash have some kind of treatment on their side, so sometimes reading an enum value involved 3 cycles of enum-to-int-to-enum translations, often with the use of an Integer box in one or two places. Slow, but it works.
The trick is to define two very similar methods:
| public static <U, T extends U> U GetValueFromHash(Hashtable hash, String key, T defaultValue, Class<U> requstedType) |
| public static int GetValueFromHash(Hashtable hash, String key, SpaceTraderEnum defaultValue, Class<Integer> requstedType) |
And use regular search/replace to push the caller’s cast as the last parameter of the call:
|
(SkillType)GetValueFromHash(hash, "_skillBonus", SkillType.NA) |
| ==> |
|
GetValueFromHash(hash, "_skillBonus", SkillType.NA, SkillType.class) |
Calls that have their default value as an enum and were cast to int are now processed by the specialized form (They don’t fit the generic form because of the <T extends U> constraint), which can find the int value of whatever is stored in the hashtable. Anything else, including calls that were previously cast to some enum, are dealt with the generic form.
Since one of our previous “fixes” happened to be changing many (if not all) of the casts to enum to use the FromInt method, we’ll fix it again with yet another search/replace to use the generic overload above.
Both method implementations are aware of the enum problem, and have special treatment for it, depending on whether or not the expression SpaceTraderEnum.class.isAssignableFrom(requstedType) holds.