How to get the initialisation value for a Java Class reference

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

    To check if a parameter of a Method is primitive, call isPrimitive(); ont the parameter type:

    Method m = ...;
    // to test the first parameter only:
    m.getParameterTypes()[0].isPrimitive();
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-04 10:37

    For completeness' sake, this is something that I think belongs to a reflection API, so I have added it to jOOR through #68

    Object init = Reflect.initValue(klass);
    

    Notably, Guava has a similar tool and there are JDK utilities that can do this as well

    0 讨论(0)
提交回复
热议问题