当类已知时创建(装箱的)原始实例
我需要一个返回所提供的类类型的实例的方法。我们假设所提供的类型仅限于可以创建它们的“空”实例。例如,提供String.class
将返回一个空字符串,提供Integer.class
将返回一个初始值为0的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
(因为它们没有空构造函数)。
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()
and
Integer.class.newInstance()
throw an InstantiationException
(because they don't have nullary constructors).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我怀疑最简单的方法是拥有一个映射:
幸运的是,所有这些类型都是不可变的,因此可以在每次调用相同类型时返回对同一对象的引用。
I suspect the simplest way is to have a map:
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.