String.format alternative on CodenameOne

Deadly 提交于 2019-12-08 05:12:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!