Java中的Void类需要什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2352447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:28:30  来源:igfitidea点击:

What is the need of Void class in Java

javavoid

提问by giri

I am not clear with the class java.lang.Voidin Java. Can anybody elaborate in this with an example.

我不清楚java.lang.VoidJava 中的类。任何人都可以举例说明这一点。

回答by TofuBeer

Say you want to have a generic that returns void for something:

假设你想要一个返回 void 的泛型:

abstract class Foo<T>
{
    abstract T bar();
}

class Bar
    extends Foo<Void>
{
    Void bar()
    {
        return (null);
    }
}

回答by axtavt

It also contains Void.TYPE, useful for testing return type with reflection:

它还包含Void.TYPE,对于使用反射测试返回类型很有用:

public void foo() {}
...
if (getClass().getMethod("foo").getReturnType() == Void.TYPE) ...

回答by Arulraj

From the Java docs:

Java 文档

public final class Void
extends Object

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

Void 类是一个不可实例化的占位符类,用于保存对表示 Java 关键字 void 的 Class 对象的引用。

static Class<Void> TYPE 

The Class object representing the primitive Java type void.

表示原始 Java 类型 void 的 Class 对象。

TYPE
public static final Class<Void> TYPE

The Class object representing the primitive Java type void.

表示原始 Java 类型 void 的 Class 对象。

回答by juancancela

Actually there is a pragmatic case where void.class is really useful. Suppose you need to create an annotation for class fields, and you need to define the class of the field to get some information about it (in example, if the field is an enum, to get list of potential values). In that case, you would need something like this:

实际上有一个务实的例子, void.class 真的很有用。假设您需要为类字段创建注释,并且需要定义该字段的类以获取有关它的一些信息(例如,如果该字段是枚举,则获取潜在值列表)。在这种情况下,你需要这样的东西:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PropertyResourceMapper
{
    public Class acceptedValues() default void.class;
}

to be used like this:

像这样使用:

@PropertyResourceMapper(acceptedValues = ImageFormat.class, description = "The format of     the image (en example, jpg).")
private ImageFormat format;

I have used this to create a custom serializer of classes to a proprietary format.

我已经用它来创建一个自定义的类序列化器到专有格式。