获取基本类型的默认值 [英] Getting default value for primitive types
问题描述
我手头有一个Java基本类型:
I have a Java primitive type at hand:
Class<?> c = int.class; // or long.class, or boolean.class
我想为该类获取一个默认值-具体来说,如果未初始化,则将该值分配给该类型的字段.例如,0
表示数字,false
表示布尔值.
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()
但是我得到的是InstantiationException
,而不是默认实例.
But I'm getting an InstantiationException
, and not a default instance.
推荐答案
Guava库已经包含以下内容:
http://guava-libraries.googlecode .com/svn/trunk/javadoc/com/google/common/base/Defaults.html
The Guava Libraries already contains that:
http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Defaults.html
调用defaultValue
将返回任何原始类型(由JLS指定)的默认值,而返回任何其他类型的默认值.
Calling defaultValue
will return the default value for any primitive type (as specified by the JLS), and null for any other type.
像这样使用它:
import com.google.common.base.Defaults;
Defaults.defaultValue(Integer.TYPE); //will return 0
这篇关于获取基本类型的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!