如何获取Java类参考的初始化值 [英] How to get the initialisation value for a Java Class reference
问题描述
我对任意类型都有 Class<?>
引用。如何获得该类型的初始化值?是否有某种图书馆方法可以解决这个问题,还是我必须自己动手,例如:
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;
用例是我有一个任意的 java.lang.reflect.Method
引用,我想使用任意参数(进行一些测试)调用该引用,如果参数是原始类型,则该引用可能不是 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.
推荐答案
要在没有第三方库的情况下执行此操作,可以创建一个数组长度一个并读出其第一个元素(通过 java.lang.reflect.Array
进行的所有操作):
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);
从Java 9开始,您还可以使用
Starting with Java 9, you could also use
Object o = MethodHandles.zero(klass).invoke();
这篇关于如何获取Java类参考的初始化值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!