如何将原始类型的 Class 对象转换为其包装器的 Class
我正在使用反射读取和写入对象。我遇到的问题是我正在以原始类型阅读;但想要告诉 read 方法将它们作为包装器读取(因此将 char 读取为 Char)。似乎应该有一个我可以调用的简单静态方法,它将采用原始类并返回它的包装类。例如,我可以提供 char.class 并返回 Char 对象的类。
我知道对此进行硬编码很容易,但这看起来很难看;看起来这种情况很常见,值得 Sun 包含一个静态辅助方法。我已经看过了,似乎找不到它,但我仍然很难相信这个方法不存在。谁能指出我该方法的名称?
谢谢。
I'm working with reflection read and writing objects. I have the problem that I am reading in primitive types; but want to tell the read method to read them as their wrapper (so read a char as a Char). It seems as if there should be a simple static method I can call which would take the primitive Class and return it's wrapper's Class. so for example I could provide char.class and get the Char object's class returned.
I know it's easy enough to hard code this, but that looks ugly; and it seems like this would come up common enough to be worth Sun including a static helper method. I've looked and can't seem to find it, but I still find it hard to believe the method doesn't exist. Can anyone point me to the name of the method?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JDK 中似乎没有任何内容,但有 Primitives 类,允许您编写:
获取
Character.class
。There appears to be nothing in the JDK, but there's the Primitives class in Guava, which allows you to write:
to get
Character.class
.在 JDK 的 tools.jar 中有一个 typeUtils.boxedClass(primitive.type) ,它处理
Symbol
对象。我知道这不是您想要的,但我会将其放入以供参考,以防万一您要查找的内容实际上就在它周围。In the JDK's tools.jar there's is
typeUtils.boxedClass(primitive.type)
which deals withSymbol
objects. I know it's not what you want, but I'll throw it in for reference and in case what you look for is actually around it.