How to get the initialisation value for a Java Class reference

后端 未结 4 1022
别那么骄傲
别那么骄傲 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:27

    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();
    

提交回复
热议问题