【Java】 Void 类型
void 也算一个类型,而且是基本数据类型
和其它数据类型一样提供了对应的包装类Void
每个包装类都提供一个TYPE字节实例,返回对应的原型类实例
public static void main(String[] args) { Class<?>[] basicTypes = { void.class, boolean.class, char.class, byte.class, short.class, int.class, long.class, float.class, double.class }; Class<?>[] wrapperTypes = { Void.class, Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class }; Class<?>[] typeInWrapperTypes = { Void.TYPE, Boolean.TYPE, Character.TYPE, Byte.TYPE, Short.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE }; System.out.println(Arrays.toString(basicTypes)); System.out.println(Arrays.toString(wrapperTypes)); System.out.println(Arrays.toString(typeInWrapperTypes)); System.out.println(Arrays.equals(basicTypes, typeInWrapperTypes)); }
基础类型void 作为方法返回类型时,不能写return,否则编译报错
但是Void类型,必须提供返回值,返回Null值
public void fun1() { // return null; } public Void fun2() { return null; }
可以通过反射设置Void类型,返回一个真实Void类型实例
public static Void fun() { try { Class<Void> voidClass = Void.class; Constructor<Void> declaredConstructor = voidClass.getDeclaredConstructor(); declaredConstructor.setAccessible(true); Void aVoid = declaredConstructor.newInstance(); System.out.println(aVoid + " by reflect"); System.out.println("aVoid == null -> " + (aVoid == null)); return aVoid; } catch (Exception e) { e.printStackTrace(); } return null; }
打印结果:
java.lang.Void@7f31245a by reflect aVoid == null -> false