在 Java 中检索存储的首选项
Preference put 和 get 方法需要并返回字符串值,但我需要使用对象(颜色),即
Preferences prefs = Preferences.userNodeForPackage(getClass());
prefs.put("savedColour", "red");
Color c = prefs.get("savedColour", "black");
显然最后一行存在类型不匹配,但我也无法将实际颜色存储在首选项中,
prefs.put("savedColour", Color.RED)
因为您需要将其存储为字符串(或整数,但不是颜色)。
有什么解决办法吗?唯一想到的就是非常混乱。
The Preference put
and get
methods require and return string values, but I need to work with objects (colours), i.e.
Preferences prefs = Preferences.userNodeForPackage(getClass());
prefs.put("savedColour", "red");
Color c = prefs.get("savedColour", "black");
Obviously there's a type mismatch on that last line, but I can't store the actual colour in prefs either,
prefs.put("savedColour", Color.RED)
because you need to store it as a string (or int, but not colour).
Any solutions to this? Only thing that comes to mind is very messy.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
也许您可以向
Color
类添加一个构造函数,该构造函数采用 String 并构建Color
实例。此外,您还应该为
Color
类实现toString()
方法。Perhaps you can add a constructor to you
Color
class that takes a String and builds theColor
instance.In addition you should implement the
toString()
method for theColor
class.如果本质上需要“序列化”对象本身,也许可以使用 Preferences API 的替代系统,例如 Xstream 或Google Gson 可能是将对象“保存”到磁盘的选项。
请注意,这比仅使用 Preferences API 更复杂,如果可以像 Tichodroma 描述的那样存储对象信息,我可能会这样做,但是您是否获得了能够表示对象的更大灵活性你感兴趣的不仅仅是字符串。
您甚至可以使用它作为 Preferences API 的补充,以便仅序列化更复杂的对象,而基础内容则保留在 Preferences 格式中。
If essentially "serializing" the objects themselves is a requirement, perhaps using an alternate system to the Preferences API like Xstream or Google Gson might be an option to "save" the objects to disk.
This would be more complex than just using the Preferences API, mind you, and if it's possble to store the object information as Tichodroma describes is possible I'd probably do that, but do you gain the increased flexibility of being able to represent the objects your interested in as more than just Strings.
You could even use it complementary to the Preferences API so that only the more complex objects are serialized, and the basics are kept in the Preferences format.
将颜色值转换为十六进制值,然后将其存储为字符串。检索它时将十六进制值解码为字符串。
Convert color value into hexadecimal value and then store it as a string. While retrieving it decode hexadecimal value into string.
有一种方法可以将对象存储在您的首选项中,但这需要几个步骤。您可以将对象转换为字节数组,将其分成 2D 字节数组中的片段,然后将字节数组存储到单个节点的槽中。以下是有关如何执行此操作的分步示例:
http://www .ibm.com/developerworks/library/j-prefapi/
There is a way to store an object in your preferences, but it takes a few steps. You can convert your object into a byte array, break it into pieces in a 2D byte array, then store the byte arrays into the slots of a single node. Here is a step-by-step example on how to do it:
http://www.ibm.com/developerworks/library/j-prefapi/