Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the initialisation value for a Java Class reference

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.

like image 747
Lukas Eder Avatar asked Oct 25 '18 11:10

Lukas Eder


2 Answers

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):

Object o = Array.get(Array.newInstance(klass, 1), 0);

Starting with Java 9, you could also use

Object o = MethodHandles.zero(klass).invoke();
like image 138
Holger Avatar answered Sep 16 '22 16:09

Holger


You can use Defaults class from guava library:

public static void main(String[] args) {
    System.out.println(Defaults.defaultValue(boolean.class));
    System.out.println(Defaults.defaultValue(int.class));
    System.out.println(Defaults.defaultValue(String.class));
}

Prints:

false
0
null
like image 23
awesoon Avatar answered Sep 19 '22 16:09

awesoon