简体   繁体   中英

How to access a variable stored in another method in java in the same class

I need to access the variable "value" in the second method. I tried making it an instance variable but it just returned as a null.

public class RateFellowUnsatisfactoryPage extends PageObject {

@FindBy(xpath = "actual xpath")
private WebElementFacade checkbox;

@FindBy(xpath = "actual xpath")
private WebElementFacade fellowRated;   

private String value;

public void selects_first_checkbox() {
    value = checkbox.getValue();
    System.out.println(value);
    checkbox.click();
}

public void verifyFellowDisplayed() {
    String fellow = fellowRated.getTextValue();
    System.out.println(fellow);
    assertThat(fellow.equalsIgnoreCase(value));
    System.out.println(value);
}
}

What you're doing looks correct. Are you sure that selects_first_checkbox has been called already at the point that you're calling verifyFellowDisplayed for this instance of RateFellowUnsatisfactoryPage? Obviously, if it has not yet been set, it will still be null.

Assuming it has been called, is it being called in the same thread? Java will sometimes optimize away references to member variables. Try declaring it volatile, which should fix it as long as you're using (I think) Java 8 or higher. If that doesn't fix it, try declaring it to be AtomicReference and you'll have an extra step to access it. Sorry, but I forget exactly what. The point of AtomicReference is that it will not optimize away any reference to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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