Java 返回一个 Void 对象

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

returning a Void object

javagenericsreturn-value

提问by Robert

What is the correct way to return a Voidtype, when it isn't a primitive? Eg. I currently use null as below.

Void当类型不是原始类型时,返回类型的正确方法是什么?例如。我目前使用 null 如下。

interface B<E>{ E method(); }

class A implements B<Void>{

    public Void method(){
        // do something
        return null;
    }
}

采纳答案by Bozho

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

So any of the following would suffice:

因此,以下任何一项就足够了:

  • parameterizing with Objectand returning new Object()or null
  • parameterizing with Voidand returning null
  • parameterizing with a NullObjectof yours
  • 参数化Object并返回new Object()null
  • 参数化Void和返回null
  • NullObject你的a 参数化

You can't make this method void, and anything else returns something. Since that something is ignored, you can return anything.

你不能制作这个方法void,其他任何东西都会返回一些东西。由于忽略了某些内容,因此您可以返回任何内容。

回答by Christopher Oezbek

There is no generic type which will tell the compiler that a method returns nothing.

没有泛型类型会告诉编译器一个方法什么都不返回。

I believe the convention is to use Object when inheriting as a type parameter

我相信约定是在作为类型参数继承时使用 Object

OR

或者

Propagate the type parameter up and then let users of your class instantiate using Object and assigning the object to a variable typed using a type-wildcard ?:

向上传播类型参数,然后让类的用户使用 Object 实例化并将对象分配给使用 type-wildcard 键入的变量?

interface B<E>{ E method(); }

class A<T> implements B<T>{

    public T method(){
        // do something
        return null;
    }
}

A<?> a = new A<Object>();

回答by Jorn

If you just don't need anything as your type, you can use void. This can be used for implementing functions, or actions. You could then do something like this:

如果您不需要任何类型作为您的类型,您可以使用 void。这可用于实现功能或操作。然后你可以做这样的事情:

interface Action<T> {
    public T execute();
}

abstract class VoidAction implements Action<Void> {
    public Void execute() {
        executeInternal();
        return null;
    }

    abstract void executeInternal();
}

Or you could omit the abstract class, and do the return null in every action that doesn't require a return value yourself.

或者您可以省略抽象类,并在每个不需要返回值的操作中自行返回 null。

You could then use those actions like this:

然后,您可以像这样使用这些操作:

Given a method

给定一个方法

private static <T> T executeAction(Action<T> action) {
    return action.execute();
}

you can call it like

你可以这样称呼它

String result = executeAction(new Action<String>() {
    @Override
    public String execute() {
        //code here
        return "Return me!";
    }
});

or, for the void action (note that you're not assigning the result to anything)

或者,对于 void 操作(请注意,您没有将结果分配给任何东西)

executeAction(new VoidAction() {
    @Override
    public void executeInternal() {
        //code here
    }
});

回答by Erick G. Hagstrom

Java 8 has introduced a new class, Optional<T>, that can be used in such cases. To use it, you'd modify your code slightly as follows:

Java 8 引入了一个新类 ,Optional<T>可以在这种情况下使用。要使用它,您需要对代码稍作修改,如下所示:

interface B<E>{ Optional<E> method(); }

class A implements B<Void>{

    public Optional<Void> method(){
        // do something
        return Optional.empty();
    }
}

This allows you to ensure that you alwaysget a non-null return value from your method, even when there isn't anything to return. That's especially powerful when used in conjunction with tools that detect when nullcan or can't be returned, e.g. the Eclipse @NonNulland @Nullableannotations.

这允许您确保始终从您的方法中获得非空返回值,即使没有任何返回值也是如此。当与检测何时null可以或不能返回的工具(例如 Eclipse@NonNull@Nullable注释)结合使用时,这尤其强大。

回答by kap

Just for the sake of it, there is of course the possibility to create Voidinstance using reflection:

只是为了它,当然可以Void使用反射创建实例:

interface B<E>{ E method(); }

class A implements B<Void>{

    public Void method(){
        // do something

        try {
            Constructor<Void> voidConstructor = Void.class.getDeclaredConstructor();
            voidConstructor.setAccessible(true);
            return voidConstructor.newInstance();
        } catch (Exception ex) {
            // Rethrow, or return null, or whatever.
        }
    }
}

You probably won't do that in production.

你可能不会在生产中这样做。