【问题标题】:Missing return value on Void method?Void 方法缺少返回值?
【发布时间】:2012-11-24 20:03:49
【问题描述】:

以下代码给了我编译时错误:缺少返回值和缺少返回语句,我将为此返回什么值Void Type

final SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
    @Override
    protected Void doInBackground() throws Exception {
        // some code
        if (something) {
            return;
        }
    }
}

【问题讨论】:

  • 使用返回空值。见stackoverflow.com/questions/643906/…
  • 由于泛型,我不能使用小写的 Void
  • @HericDenis:那么你应该明白你确实需要返回一些东西(可能是一个空引用)......它不仅仅是一个没有返回值的普通 void 方法。
  • 我会返回 null,但我想:idk 可能会发生一些 nullPointerException,这太疯狂了

标签: java generics


【解决方案1】:

检查这个。它要求返回Void 大写“V”而不是简单的void

final SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
    @Override
    protected Void doInBackground() throws Exception {
        // my code here
        return null;
    }
}

【讨论】:

    【解决方案2】:

    Void 不是void,如果不想返回任何内容,请将其更改为 void 类型。

    void 是类,void 是类型。

    /**
     * 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
     */
    

    如果你想要Void,那么你需要在末尾添加return声明。

    例子:

    protected Void doInBackground() throws Exception {
        // some code
        if (something) {
           return null;
        }
        return null;
    }
    

    【讨论】:

    • 谢谢,这就是我的想法,但我不确定它是否会给出一些 NullPointerException 或其他东西。谢谢
    • @HericDenis:我认为它不会失败。请参阅此讨论stackoverflow.com/questions/4261666/…
    • 第一个return语句后缺少一个null
    • 是的,看起来像 :) 谢谢@Nambari
    猜你喜欢
    • 2013-03-31
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 2022-12-11
    • 1970-01-01
    相关资源
    最近更新 更多