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.
So I assume that for primitives like int.class
you want to return new Integer(0)
, but for lets say Objects you want to return null
.
If that is true you can use fact that arrays are filled with default values at start. Try maybe this way
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)
will create array of type clazz
with one default element,
Array.get(<someArray>, 0)
will return its first element.
- also since your method
defaultValue
returns Object it will be autoboxed to corresponding type int
->Integer
.
Example
System.out.println(defaultValue(int.class));
System.out.println(defaultValue(int.class).getClass());
prints
0
class java.lang.Integer