获取原始类型的默认值
我手头有一个 Java 原始类型:
Class<?> c = int.class; // or long.class, or boolean.class
我想获得该类的默认值——具体来说,如果该类型的字段未初始化,则将该值分配给该类型的字段。例如,0
表示数字,false
表示布尔值。
有没有通用的方法来做到这一点?我尝试了这个:
c.newInstance()
但是我收到了 InstantiationException
,而不是默认实例。
I have a Java primitive type at hand:
Class<?> c = int.class; // or long.class, or boolean.class
I'd like to get a default value for this class -- specifically, the value is assigned to fields of this type if they are not initialized. E.g., 0
for a number, false
for a boolean.
Is there a generic way to do this? I tried this:
c.newInstance()
But I'm getting an InstantiationException
, and not a default instance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
Guava 库已经包含:
http://guava-libraries.googlecode .com/svn/trunk/javadoc/com/google/common/base/Defaults.html
调用
defaultValue
将返回任何基元类型的默认值(由 JLS 指定),对于任何其他类型,则为 null。像这样使用它:
The Guava Libraries already contains that:
http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Defaults.html
Calling
defaultValue
will return the default value for any primitive type (as specified by the JLS), and null for any other type.Use it like so:
通过创建一个元素的数组并检索其第一个值,可以获取任何类型的默认值。
这样,就不需要考虑每一种可能的基本类型,而创建单元素数组的成本通常可以忽略不计。
It's possible to get the default value of any type by creating an array of one element and retrieving its first value.
This way there is not need to take account for every possible primitive type, at the usually negligible cost of creating a one-element array.
这就是我的想法(尽管没有通过优雅测试):
This is what I'm thinking (fails the elegance test though):
Guava 的
Defaults.java
的替代方案,它可以让实现计算出默认值(通过使用 Antag99 的答案进行改进):An alternative to Guava's
Defaults.java
, which lets the implementation figure out the default values (improved by using Antag99’s answer):您可以通过反射来完成此操作,但最简单、最清晰的方法是将其写出来,例如,
当然,您可能希望将映射初始化移至构造函数或类似的构造函数中以进行一次性初始化。
相当简洁——优雅?
You can do this with reflection, but it's easiest and clearest to write it out, e.g.
Of course, you will probably want to move the map initialization out to a constructor or similar for once-only initialization.
Reasonably concise - it is elegant?
没有一种优雅的方法可以做到这一点。事实上,甚至不可能声明返回原始值本身的方法的签名。
你能得到的最接近的是这样的:
There isn't an elegant way to do this. In fact, it is not even possible to declare the signature of a method that will return the primitive values per se.
The closest you can come is something like this:
基元的类变量不需要初始化或设置默认值。但是,在其他作用域中声明的变量必须进行初始化,否则您将收到编译错误。
}
Class variables of primitives do not need to be initialized or set with a default value. However variables declare in other scope must be initialized or you'll get compilation errors.
}
如果您想要包含字符串数据类型的默认值,请尝试此操作:
Try this if you want default value including String data type:
基于Jack Leow 的回答,我创建了这个类:
Based on Jack Leow's answer, I created this class: