void 和 Void 是 Java 类型系统中两个密切相关但用途完全不同的概念。它们都表明“无返回值”或“无类型”,但在语法、语义和使用场景上有显著区别。
一、核心对比
|
特性 |
void |
Void |
|
类型 |
基本类型(关键字) |
引用类型(类) |
|
是否可以声明变量 |
❌ 不可以 |
可以,但只能赋值为 null |
|
能否用于泛型 |
❌ 不能 |
能,如 Future<Void> |
|
主要用途 |
方法返回类型 |
泛型占位符、反射 |
二、void—— 关键字,表明“无返回值”
用途:用于方法声明,表明该方法不返回任何值。
public void doSomething() {
System.out.println("Doing something...");
// 没有 return 值,或 return;(可选)
}
不能用于变量声明
void x = 10; // 编译错误!
void result = func(); // 错误!void 不是类型,不能赋值
三、Void—— 类,表明“无类型的包装”
定义
public final class Void {
public static final Class<Void> TYPE = (Class<Void>) Class.getPrimitiveClass("void");
// 私有构造器,不能实例化
private Void() {}
}
- Void 是一个 final 类,位于 java.lang 包。
- 你不能创建 Void 的实例(构造器私有)。
- 唯一的“值”是 null。
合法用法:变量只能是 null
Void v = null; // 正确
// Void v = new Void(); // 编译错误!构造器私有
System.out.println(v); // 输出: null
四、为什么需要 Void?—— 主要用途
1. 泛型中的占位符(最常见)
当你使用泛型,但不需要返回值时,可以用 Void 占位。
示例:Future<V>在异步任务中
import java.util.concurrent.*;
public class Test {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
// 提交一个无返回值的任务,但想用 Future 来管理它
Future<Void> future = executor.submit(() -> {
System.out.println("Task running...");
return null; // 必须返回 null
});
future.get(); // 等待完成
executor.shutdown();
}
}
这里 Future<Void> 表明:“这个任务没有有意义的返回值”。
2. 反射(Reflection)中表明无返回类型
package net.skystudio.demo;
import java.lang.reflect.Method;
public class Test {
public void hello() {
System.out.println("Hello");
}
public static void main(String[] args) throws Exception {
Method m = Test.class.getMethod("hello");
System.out.println(m.getReturnType()); // 输出: void
System.out.println(m.getReturnType() == Void.TYPE); // true
System.out.println(m.getReturnType() == void.class); // true
System.out.println(void.class == Void.TYPE); // true
}
}
void.class 和 Void.TYPE 是同一个东西!
3. 函数式编程中作为泛型参数
// 表明一个不返回结果的操作
Supplier<Void> action = () -> {
System.out.println("Action executed");
return null;
};
action.get(); // 执行
五、最佳实践提议
- 方法返回空 → 用 void
- 泛型需要“无返回”占位 → 用 Void
- 反射中比较返回类型 → 用 void.class 或 Void.TYPE
- 不要滥用 Void,它只在特定场景下有用
© 版权声明
文章版权归作者所有,未经允许请勿转载。






学到了💪