How to get the initialisation value for a Java Class reference

你离开我真会死。 提交于 2019-11-30 16:51:38

问题


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.


回答1:


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



回答2:


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



回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/52988458/how-to-get-the-initialisation-value-for-a-java-class-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!