java.lang.Void类的解析与使⽤详解今天在查看源码的时候发现了 java.lang.Void 的类。这个有什么作⽤呢?
springboot实现aop
先通过源码查看下
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>) PrimitiveClass("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>) PrimitiveClass("void");
Void 使⽤
Void类是⼀个不可实例化的占位符类,如果⽅法返回值是Void类型,那么该⽅法只能返回null类型。⽰例如下:
public Void test() {
return null;
}
使⽤场景⼀:
Future<Void> f = pool.submit(new Callable() {
@Override
public Void call() throws Exception {
......
return null;
}
});
⽐如使⽤ Callable接⼝,该接⼝必须返回⼀个值,但实际执⾏后没有需要返回的数据。这时可以使⽤Void类型作为返回类型。
使⽤场景⼆:
通过反射获取所有返回值为void的⽅法。
public class Test {
public void hello() { }
public static void main(String args[]) {
for (Method method : Methods()) {
if (ReturnType().equals(Void.TYPE)) {
System.out.Name());
}
}
}
}
执⾏结果:
main
hello
wait
wait
wait
notify
notifyAll
ps:下⾯介绍java.lang.Void 与 void的⽐较及使⽤
void关键字表⽰函数没有返回结果,是java中的⼀个关键字。
java.lang.Void是⼀种类型。例如给Void引⽤赋值null。
Void nil = null;
通过Void类的代码可以看到,Void类型不可以继承与实例化。
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>) PrimitiveClass("void");
/*
* The Void class cannot be instantiated.
*/
private Void() {}
}
Void作为函数的返回结果表⽰函数返回null(除了null不能返回其它类型)。
Void function(int a, int b) {
/
/do something
return null;
}
在泛型出现之前,Void⼀般⽤于反射之中。例如,下⾯的代码打印返回类型为void的⽅法名。
public class Test {
public void print(String v) {}
public static void main(String args[]){
for(Method method : Methods()) {
ReturnType().equals(Void.TYPE)) {
System.out.Name());
}
}
}
}
泛型出现后,某些场景下会⽤到Void类型。例如Future<T>⽤来保存结果。Future的get⽅法会返回结果(类型为T)。
但如果操作并没有返回值呢?这种情况下就可以⽤Future<Void>表⽰。当调⽤get后结果计算完毕则返回后将会返回null。
另外Void也⽤于⽆值的Map中,例如Map<T,Void>这样map将具Set<T>有⼀样的功能。
因此当你使⽤泛型时函数并不需要返回结果或某个对象不需要值时候这是可以使⽤java.lang.Void类型表⽰。
总结
以上所述是⼩编给⼤家介绍的java.lang.Void的类解析与使⽤详解,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。在此也⾮常感谢⼤家对⽹站的⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。