简体   繁体   English

Java if () 语句总是假的?

[英]Java if () statement always false?

In the 20+ years I've been programming in Java, I've never come across anything as puzzling as this.在我在 Java 中编程的 20 多年里,我从未遇到过如此令人费解的事情。 In the following code:在以下代码中:

        // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
    currentUser = mAuth.getCurrentUser();
    if (currentUser == null) {
        LoginManager.getInstance().logOut();
        LoginFragment loginFragment = new LoginFragment();
        FragmentManager manager = getActivity().getSupportFragmentManager();
        manager.beginTransaction().replace(R.id.fragment_container, loginFragment, loginFragment.getTag()).commit();
        return view;
    }
    firebase_userID = currentUser.getUid();

I set a breakpoint at the if() statement and when I get there, I set the variable, currentUser, to null.我在 if() 语句处设置了一个断点,当我到达那里时,我将变量 currentUser 设置为 null。 When I resume execution, the statement LoginManager.getInstance().logOut() should execute, right?当我恢复执行时,语句 LoginManager.getInstance().logOut() 应该执行,对吗? Instead, the code falls through to the line after the if().相反,代码会一直到 if() 之后的行。 Why on earth should this happen??为什么会发生这种情况??

To prove that I'm not dreaming, here are the relevant screenshots:为了证明我不是在做梦,下面是相关截图: 在此处输入图像描述 and在此处输入图像描述

And yes, I did rebuild and reload the app after adding the if() statement.是的,在添加 if() 语句后,我确实重建并重新加载了应用程序。 I even restarted Android Studio.我什至重新启动了 Android Studio。

As per my understanding and experience, when a code is changed dynamically when in debug mode, it tries to run again from the point where breakpoint is given so that purpose of debugging is served and you do not need to trigger it again.根据我的理解和经验,在调试模式下动态更改代码时,它会尝试从给出断点的点再次运行,以便达到调试目的,您无需再次触发它。 Once any exception is thrown or manually current thread execution is made over then it will not come back to if statement.一旦抛出任何异常或手动完成当前线程执行,它将不会返回到 if 语句。 In that case it has to be re triggered again to execute with the changes done.在这种情况下,必须再次重新触发它才能在更改完成后执行。

I moved the declaration of currentUser to inside createView() and the problem went away.我将 currentUser 的声明移到 createView() 内部,问题就消失了。 I don't understand why that should make a difference, especially since the identical code in a similar app doesn't have this problem and currentUser is declared global.我不明白为什么这会有所不同,特别是因为类似应用程序中的相同代码没有这个问题,并且 currentUser 被声明为全局的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM