How to get the initialisation value for a Java Class reference

后端 未结 4 985
别那么骄傲
别那么骄傲 2021-01-04 09:52

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 rol

4条回答
  •  轮回少年
    2021-01-04 10:36

    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
    

提交回复
热议问题