Java Void 引用类型的用途?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/643906/
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-11 17:19:22  来源:igfitidea点击:

Uses for the Java Void Reference Type?

javavoid

提问by Julien Chastang

There is a Java Void-- uppercase V-- reference type. The only situation I have ever seen it used is to parameterize Callables

有一个 Java Void- 大写 V -引用类型。我见过它使用的唯一情况是参数化Callables

final Callable<Void> callable = new Callable<Void>() {
            public Void call() {
                foobar();
                return null;
            }
        };

Are there any other uses for the Java Voidreference type? Can it ever be assigned anything other than null? If yes, do you have examples?

JavaVoid引用类型还有其他用途吗?除了null? 如果是,你有例子吗?

采纳答案by Tom Hawtin - tackline

Voidhas become convention for a generic argument that you are not interested in. There is no reason why you should use any other non-instantiable type, such as System.

Void已成为您不感兴趣的泛型参数的约定。没有理由您应该使用任何其他不可实例化的类型,例如System.

It is also often used in for example Mapvalues (although Collections.newSetFromMapuses Booleanas maps don't have to accept nullvalues) and java.security.PrivilegedAction.

它也经常在示例中使用Map的值(虽然Collections.newSetFromMap使用Boolean的地图不具有接受null值)和java.security.PrivilegedAction

I wrote a weblog entryon Voida few years back.

我写了一篇博客文章Void几年前。

回答by Alexander Temerev

Future<Void>works like charm. :)

Future<Void>像魅力一样工作。:)

回答by Michael Myers

Given that there are no public constructors, I would say it can't be assigned anything other than null. I've only used it as a placeholder for "I don't need to use this generic parameter," as your example shows.

鉴于没有公共构造函数,我会说除了null. 正如您的示例所示,我仅将其用作“我不需要使用此通用参数”的占位符。

It could also be used in reflection, from what its Javadocsays:

它也可以用于反射,从它的Javadoc说:

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 对象的引用。

回答by Peter Lawrey

You can create instance of Void using reflections, but they are not useful for anything. Void is a way to indicate a generic method returns nothing.

您可以使用反射创建 Void 实例,但它们对任何事情都没有用。void 是一种表示泛型方法不返回任何内容的方式。

Constructor<Void> constructor = Void.class.getDeclaredConstructor();
constructor.setAccessible(true);
Void v = constructor.newInstance();
System.out.println("I have a " + v);

prints something like

打印出类似的东西

I have a java.lang.Void@75636731

回答by Luke Woodward

All the primitive wrapper classes (Integer, Byte, Boolean, Double, etc.) contain a reference to the corresponding primitive class in a static TYPEfield, for example:

所有原始包装类(IntegerByteBooleanDouble等)都在静态TYPE字段中包含对相应原始类的引用,例如:

Integer.TYPE == int.class
Byte.TYPE == byte.class
Boolean.TYPE == boolean.class
Double.TYPE == double.class

Voidwas initially created as somewhere to put a reference to the voidtype:

Void最初被创建为放置对void类型的引用的地方:

Void.TYPE == void.class

However, you don't really gain anything by using Void.TYPE. When you use void.classit's much clearer that you're doing something with the voidtype.

但是,使用Void.TYPE. 当你使用void.class它时,你会更清楚地知道你正在用void类型做一些事情。

As an aside, the last time I tried it, BeanShelldidn't recognise void.class, so you have to use Void.TYPEthere.

顺便说一句,我上次尝试时,BeanShell无法识别void.class,因此您必须在Void.TYPE那里使用。

回答by Lawrence Dol

Before generics, it was created for the reflection API, to hold TYPE returned by Method.getReturnType() for a void method, corresponding to the other primitive type classes.

在泛型之前,它是为反射 API 创建的,用于保存 Method.getReturnType() 为 void 方法返回的 TYPE,对应于其他基本类型类。

EDIT: From the JavaDoc of Void: "The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void". Prior to Generics, I am aware of no use other than reflection.

编辑:来自 Void 的 JavaDoc:“Void 类是一个不可实例化的占位符类,用于保存对表示 Java 关键字 void 的 Class 对象的引用”。在泛型之前,我知道除了反射没有其他用处。

回答by Adelin

Void is create to wrap its primitive void type. Every primitive type has it's corresponding Reference type. Void is used to instantiate a generic class or use of a generic method, A generic arguments witch you are not interested in. and here is an example ...

创建 Void 是为了包装其原始的 void 类型。每个原始类型都有其对应的引用类型。Void 用于实例化泛型类或使用泛型方法,你不感兴趣的泛型参数。这里是一个例子......

public void onNewRegistration() {
    newRegistrationService.createNewUser(view.getUsername(), view.getPassword(),
            view.getInitialAmount(), view.getCurrency(), new AsyncCallback<Void>() {
      @Override
      public void onFailure(Throwable caught) {

      }

      @Override
      public void onSuccess(Void result) {
        eventBus.fireEvent(new NewRegistrationSuccessEvent());
      }
    });
  } 

here,as you can see, i don't want anything from the server that i am asking to create a new registrations,but public interface AsyncCallback<T> { .... }is a generic interface so i provide Void since generics don't accept primitive types

在这里,如您所见,我不希望服务器提供任何我要求创建新注册的内容,但它public interface AsyncCallback<T> { .... }是一个通用接口,因此我提供了 Void,因为泛型不接受原始类型

回答by Ronan Quillevere

When you use the visitor patternit can be cleaner to use Void instead of Object when you want to be sure that the return value will be null

当您使用访问者模式时,当您想确保返回值将为空时,使用 Void 而不是 Object 会更清晰

Example

例子

public interface LeavesVisitor<OUT>
{
   OUT visit(Leaf1 leaf);

   OUT visit(Leaf2 leaf);
}

When you will implement your visitor you can explicitly set OUT to be Void so that you know your visitor will always return null, instead of using Object

当您实现您的访问者时,您可以明确地将 OUT 设置为 Void,以便您知道您的访问者将始终返回 null,而不是使用 Object

public class MyVoidVisitor implements LeavesVisitor<Void>
{
    Void visit(Leaf1 leaf){
        //...do what you want on your leaf
        return null;
    }

    Void visit(Leaf2 leaf){
        //...do what you want on your leaf
        return null;
    }
}

回答by eckes

It is also commonly used on Async-IO completion callbacks when you dont have the need for an Attachmentobject. In that case you specify null to the IO operation and implement CompletionHandler<Integer,Void>.

当您不需要Attachment对象时,它也常用于 Async-IO 完成回调。在这种情况下,您为 IO 操作指定 null 并实现CompletionHandler<Integer,Void>.

回答by Mar Bar

As you can't instantiate Void, you can use Apache commons Null object, so

由于您无法实例化 Void,您可以使用Apache commons Null object,因此

Null aNullObject = ObjectUtils.Null;
Null noObjectHere = null;

in the first line, you have an object, so aNullObject != nullholds, while in the second line there is no reference, so noObjectHere == nullholds

在第一行,你有一个对象,所以aNullObject != null成立,而在第二行没有引用,所以noObjectHere == null成立

To answer the poster's original question, the usage for this is to differentiate between "the nothing" and "nothing", which are completely different things.

为了回答发帖人的原始问题,this 的用法是区分“无”和“无”,它们是完全不同的东西。

PS: Say no to Null object pattern

PS:对空对象模式说不