I have a Class<?>
reference for an arbitrary type. How to get that type's initialisation value? Is there some library method for this or do I have to roll my own, such as:
Class<?> klass = ...
Object init =
(klass == boolean.class)
? false
: (klass == byte.class)
? (byte) 0
...
: (Object) null;
The use case is I have an arbitrary java.lang.reflect.Method
reference, which I want to call using arbitrary parameters (for some testing), which may not be null
in case the parameter is a primitive type, so I need to specify some value of that type.
To do it without 3rd party libraries, you may create an array of length one and read out its first element (both operations via
java.lang.reflect.Array
):Starting with Java 9, you could also use
To check if a parameter of a Method is primitive, call
isPrimitive();
ont the parameter type:For completeness' sake, this is something that I think belongs to a reflection API, so I have added it to jOOR through #68
Notably, Guava has a similar tool and there are JDK utilities that can do this as well
You can use
Defaults
class from guava library:Prints: