I have a Java primitive type at hand:
Class<?> c = int.class; // or long.class, or boolean.class
I'd like to get a default value for this class -- specifically, the value is assigned to fields of this type if they are not initialized. E.g., 0
for a number, false
for a boolean.
Is there a generic way to do this? I tried this:
c.newInstance()
But I'm getting an InstantiationException
, and not a default instance.
Remember, to get the default values, you do not need to assign values to the variable. static boolean val1; static double val2; static float val3; static int val4; static long val5; static String val6; Now to display the default values, you need to just print the variables.
The minimum value char can hold is 'u0000' which is a Unicode value denoting 'null' or 0 in decimal. The maximum value it can hold is 'uffff' or 65,535 inclusive. The minimum value which is 'u0000' is also the default value of char.
The Guava Libraries already contains that:
http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Defaults.html
Calling defaultValue
will return the default value for any primitive type (as specified by the JLS), and null for any other type.
Use it like so:
import com.google.common.base.Defaults; Defaults.defaultValue(Integer.TYPE); //will return 0
It's possible to get the default value of any type by creating an array of one element and retrieving its first value.
private static <T> T getDefaultValue(Class<T> clazz) { return (T) Array.get(Array.newInstance(clazz, 1), 0); }
This way there is not need to take account for every possible primitive type, at the usually negligible cost of creating a one-element array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With