问题
I'm trying to port a Java-based library to CodenameOne in order to use it in a cross-platform project but it uses a lot of Java standard APIs that I cannot find in CodenameOne, first of all String.format
.
I have read this Q&A and I understood there are a few utility libraries which implement what's missing in base classes.
Is there a library class which implements String.format
?
As an example, I need to do something like String.format("%02d:%02d:%02d", hh, mm, ss);
回答1:
You can use com.codename1.l10n.SimpleDateFormat
to format time although personally I just use utility Java code to format as it's simpler. With Date
we get into the timezone complexities and that's a pain in the neck.
I just usually do:
public static String twoDigits(int v) {
return v < 10 ? "0" + v : "" + v;
}
Then:
String t = twoDigits(hh) + ":" + twoDigits(mm) + ":" + twoDigits(ss);
Notice that this code is more efficient than the Format
code. The Format
call needs to parse the formatting then generate the resulting string which is a costly step. Probably won't be noticeable for most cases though.
The main problem we have with String.format()
is it's presence in String
. Since String is a core part of the implementation a complex method like that will add weight to every application regardless of need. Also implementing a method like that with so many nuances would mean things would work differently on the simulator than on the device. So it's highly unlikely that we'll ever add that method.
In fact on JavaSE that method is really just a form of MessageFormat
which is something we could add in the codename1 l10n package. Incompatibility wouldn't be a problem and neither would size/complexity. This is something you can implement yourself and even submit as a pull request if you so desire. You can base your implementation on the Apache licensed harmony project sources or you can build a clean room implementation (which I often found to be easier).
来源:https://stackoverflow.com/questions/53390230/string-format-alternative-on-codenameone