且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

这是为什么Java的code执行多个return语句

更新时间:2023-11-05 22:50:04

有可能是没有任何问题与此有关。编译器可能编译返回RETVAL 如果语句转换跳转到一个跳转里面的返回在函数的结束,这的有一个返回RETVAL 语句。显示奇流量控制调试器的的意思是有什么不妥。

I have a function that during execution while in the debuger runs both the return statment inside the if and then the return statment at the end of the function.

I'm confused I thought the return statment returned the value and stopped the flow of execution in the method?

I've got it to work, but would like to understand why it is doing this.

As an example in the below. The json will fail on the answer adn the createapprove block. It gets to create fail and ret becomes true (As the json parsed). The return retval runs and then the code jumps down to the final return retval and executes that as the return for the function.

I'm walking through the code in ecipse in debug mode with the program running on the android emulator.

public static ComModelFromServer createModelFromJSON(String json) throws JSONInvalidException {     
     boolean ret = false;
     ComModelFromServer retval = null;

     //Answer Block
     Answer a = new AnswerAsset();
     ret = a.tryToParseFromJSON(json);
     if(ret == true) {
        retval = a;
        return retval;
    }

    Create cr = new CreateApprove();
    ret = cr.tryToParseFromJSON(json);
    if(ret == true) {
        retval = cr;
        return retval;
    }

    cr = new CreateFail();
    ret = cr.tryToParseFromJSON(json);
    if(ret == true) {
        retval = cr;
        return retval;
    }

    if(ret == false) { 
        throw new JSONInvalidException("couldn't create model from JSON");
    }

    return retval;
}

There's probably no problem with this. The compiler probably compiled the return retval inside the if statements into a jump that jumps to the return at the end of the function, which already has a return retval statement. The debugger showing the odd flow control doesn't mean that there is anything wrong.