在知道类时创建(盒装)原始实例

我需要一个方法来返回提供的类类型的实例。 假设所提供的类型被限制为可以创建它们的“空”实例。 例如,提供String.class将返回一个空String,提供Integer.class将返回一个初始值为零的Integer,依此类推。 但是我如何动态创建(盒装)原始类型? 像这样?

 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.... } } 

迭代所有可能的原始类型的唯一解决方案,还是有更简单的解决方案? 请注意两者

 int.class.newInstance() 

 Integer.class.newInstance() 

抛出InstantiationException (因为它们没有nullary构造函数)。

我怀疑最简单的方法是有一张地图:

 private final static Map, Object> defaultValues = new HashMap, 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 } 

幸运的是,所有这些类型都是不可变的,因此可以在每次调用时为同一类型返回对同一对象的引用。