java.lang.Void 解析与使用
生活随笔
收集整理的这篇文章主要介绍了
java.lang.Void 解析与使用
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
今天在查看源码的时候发现了 java.lang.Void 的类。这个有什么作用呢?
先通过源码查看下
package java.lang;/*** The {@code Void} class is an uninstantiable placeholder class to hold a* reference to the {@code Class} object representing the Java keyword* void.** @author unascribed* @since JDK1.1*/ public final class Void {/*** The {@code Class} object representing the pseudo-type corresponding to* the keyword {@code void}.*/@SuppressWarnings("unchecked")public static final Class<Void> TYPE = (Class<Void>) Class.getPrimitiveClass("void");/** The Void class cannot be instantiated.*/private Void() {} }从源码中发现该类是final的,不可继承,并且构造是私有的,也不能 new。
那么该类有什么作用呢?
下面是我们先查看下 java.lang.Integer 类的源码
我们都知道 int 的包装类是 java.lang.Integer
从这可以看出 java.lang.Integer 是 int 的包装类。
同理,通过如下 java.lang.Void 的源码可以看出 java.lang.Void 是 void 关键字的包装类。
public static final Class<Void> TYPE = (Class<Void>) Class.getPrimitiveClass("void");Void 使用
Void类是一个不可实例化的占位符类,如果方法返回值是Void类型,那么该方法只能返回null类型。
示例如下:
使用场景一:
Future<Void> f = pool.submit(new Callable() {@Overridepublic Void call() throws Exception {......return null;}});比如使用 Callable接口,该接口必须返回一个值,但实际执行后没有需要返回的数据。 这时可以使用Void类型作为返回类型。
使用场景二:
通过反射获取所有返回值为void的方法。
public class Test {public void hello() { }public static void main(String args[]) {for (Method method : Test.class.getMethods()) {if (method.getReturnType().equals(Void.TYPE)) {System.out.println(method.getName());}}} }执行结果:
main hello wait wait wait notify notifyAll想了解更多精彩内容请关注我的公众号
本人简书blog地址:http://www.jianshu.com/u/1f0067e24ff8
点击这里快速进入简书
GIT地址:http://git.oschina.net/brucekankan/
点击这里快速进入GIT
总结
以上是生活随笔为你收集整理的java.lang.Void 解析与使用的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: Java 注解 Annotation
- 下一篇: 网络传输 相关概念