Api Design Regarding File Tokenization, Object Value Setting And Enums Of Token Positions
In my Android application I need to read a large amount of data from a set of .ini files that were originally (and still are) deployed with a Windows application. The application i
Solution 1:
What you are trying to do is not possible with Java enums. However it could be easily achieved in the other way:
publicclassIniParam<T> {
publicstaticfinal IniParam<String> NAME = new IniParam<String>(2);
publicstaticfinal IniParam<String> UNITS = new IniParam<String>(3);
publicstaticfinal IniParam<Integer> LOWER = new IniParam<Integer>(4);
publicstaticfinal IniParam<Integer> UPPER = new IniParam<Integer>(5);
privatefinalint position;
private IniParam(int position) {
this.position = position;
}
publicint getPosition() {
return position;
}
}
Tokenizer then may look like:
publicclassTokenizer {
publicStringget(IniParam<String> iniParam) {
int position = iniParam.getPosition();
//...return"some string from .ini";
}
public int get(IniParam<Integer> iniParam) {
// ... // return some integer from .ini
}
}
Usage example:
Tokenizer t = new Tokenizer();
String name = t.get(IniParam.NAME);
int lower = t.get(IniParam.LOWER);
someObject.setName( t.get(IniParam.NAME) ).setUnits( t.get(IniParam.UNITS) ).setLowerUpper( t.get(IniParam.LOWER), t.get(IniParam.UPPER) );
UPDATE
Unfortunately Tokenizer
class I provided above will not compile with JDK 7/Eclipse 3.6+ compilers (I can't check it myself right now but the fixes for the following Oracle and Eclipse bugs suppose compilation errors in get(...)
methods). If you face this issue here is the workaround:
publicclassIniParam<T> {
publicstatic final IniParam<String> NAME = newIniParam<String>(2, String.class);
publicstatic final IniParam<String> UNITS = newIniParam<String>(3, String.class);
publicstatic final IniParam<Integer> LOWER = newIniParam<Integer>(4, Integer.class);
publicstatic final IniParam<Integer> UPPER = newIniParam<Integer>(5, Integer.class);
private final int position;
private final Class<? extends T> type;
privateIniParam(int position, Class<? extends T> type) {
this.position = position;
this.type = type;
}
public int getPosition() {
return position;
}
publicClass<? extends T> getType() {
returntype;
}
}
publicclassTokenizer {
public <T> T get(IniParam<T> iniParam) {
int position = iniParam.getPosition();
Class<? extends T> type = iniParam.getType();
if (type == String.class) {
//...returntype.cast("some string from .ini");
} elseif (type == Integer.class) {
//...// Integer result = ...;returntype.cast(result);
} else {
thrownewIllegalArgumentException("Unexpected IniParam type: " + type);
}
}
}
Post a Comment for "Api Design Regarding File Tokenization, Object Value Setting And Enums Of Token Positions"