如何编写一个返回给定类默认值的函数?如果一个类是基元之一,它应该返回一个具有默认值的包装类,否则返回 null。
public <B> Object defaultValue(Class<B> clazz) {
return clazz.isPrimitive() ? ... : null;
}
所以对于 int.class
它应该返回 Integer(0)
。
最佳答案
How do I write a function which returns a default value for the given class? If a class is one of the primitives it should return a wrapper class with default value, else return null.
所以我假设对于像 int.class
这样的原语你想返回 new Integer(0)
,但让我们说您要返回的对象 null
.
如果这是真的,你可以使用数组在开始时填充默认值的事实。试试这个方法
import java.lang.reflect.Array;
...
public static <B> Object defaultValue(Class<B> clazz) {
return Array.get(Array.newInstance(clazz, 1),0);
}
-
Array.newInstance(clazz, 1)
将创建类型为clazz
的数组使用一个默认元素, -
Array.get(<someArray>, 0)
将返回它的第一个元素。 - 也因为你的方法
defaultValue
返回对象,它将被自动装箱到相应的类型int
->Integer
.
例子
System.out.println(defaultValue(int.class));
System.out.println(defaultValue(int.class).getClass());
打印
0
class java.lang.Integer
关于java - 类的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16282961/