当类已知时创建(盒装)原始实例 [英] Creating (boxed) primitive instance when the class is known
问题描述
我需要一个方法来返回提供的类类型的实例。让我们假设所提供的类型被限制为使得可以创建它们的空实例。例如,提供 String.class
将返回一个空的String,提供一个 Integer.class
将返回一个Integer,值为零,以此类推。但是如何在运行中创建(盒装)原始类型?像这样?
I need a method that returns an instance of the supplied class type. Let's assume that the supplied types are limited to such that an "empty" instance of them can be created. For instance, supplying String.class
would return an empty String, supplying an Integer.class
would return an Integer whose initial value is zero, and so on. But how do I create (boxed) primitive types on the fly? Like this?
public Object newInstance(Class<?> type) {
if (!type.isPrimitive()) {
return type.newInstance(); // plus appropriate exception handling
} else {
// Now what?
if (type.equals(Integer.class) || type.equals(int.class)) {
return new Integer(0);
}
if (type.equals(Long.class) // etc....
}
}
是唯一可以遍历所有可能的原始类型的解决方案,还是有一个更直接的解决方案?注意
Is the only solution to iterate through all the possible primitive types, or is there a more straightforward solution? Note that both
int.class.newInstance()
Integer.class.newInstance()
抛出 InstantiationException
(因为它们没有nullary构造函数)。
throw an InstantiationException
(because they don't have nullary constructors).
推荐答案
我怀疑最简单的方法是有一张地图:
I suspect the simplest way is to have a map:
private final static Map<Class<?>, Object> defaultValues =
new HashMap<Class<?>, Object>();
static
{
defaultValues.put(String.class, "");
defaultValues.put(Integer.class, 0);
defaultValues.put(int.class, 0);
defaultValues.put(Long.class, 0L);
defaultValues.put(long.class, 0L);
defaultValues.put(Character.class, '\0');
defaultValues.put(char.class, '\0');
// etc
}
幸运的是,所有这些类型都是不可变的,因此可以在每次调用相同类型的对象时返回对同一对象的引用。
Fortunately all these types are immutable, so it's okay to return a reference to the same object on each call for the same type.
这篇关于当类已知时创建(盒装)原始实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!