Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
897 views
in Technique[技术] by (71.8m points)

java - Circular Dependency in classes and StackOverflow Error

Though the practice that I have been following could be inappropriate. Still looking for a fix to my problem here :

I'm getting a StackOverflowError ::

java.lang.StackOverflowError
    at com.my.package.pages.Selendroid.HomePage.<init>(HomePage.java:11)
    at com.my.package.pages.Selendroid.LoginPage.<init>(LoginPage.java:14)
    at com.my.package.pages.Selendroid.HomePage.<init>(HomePage.java:11)

AppiumBasePage ::

public class AppiumBasePage {
    protected AppiumDriver driver;

HomePage ::

public class HomePage extends AppiumBasePage {
    LoginPage loginPage = new LoginPage();

LoginPage ::

public class LoginPage extends AppiumBasePage {
    HomePage homePage = new HomePage();

Q : How do I resolve this cyclic dependency and what exactly am I doing wrong here? Details would be great.

Edit : The details to what I want to achieve is - I would be having a lot of interrelated methods in both these classes. And instead of creating an object inside the functions where I wanted to use it multiple times, I want to have a single object of one page on another to use the methods defined in the former.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem is that when you create a HomePage it creates a new LoginPage and whenever you create a LoginPage you create a HomePage. This will clearly result in a never ending (until the stack overflows) cycle.

To solve the problem, do not create the pages during construction. Make setters for them

private static class AppiumBasePage {

    public AppiumBasePage() {
    }
}

public class HomePage extends AppiumBasePage {

    LoginPage loginPage;

    public void setLoginPage(LoginPage loginPage) {
        this.loginPage = loginPage;
    }

}

public class LoginPage extends AppiumBasePage {

    HomePage homePage;

    public void setHomePage(HomePage homePage) {
        this.homePage = homePage;
    }


}

public void test() {
    LoginPage login = new LoginPage();
    HomePage home = new HomePage();
    login.setHomePage(home);
    home.setLoginPage(login);
}

Alternatively you could remove the interdependency entirely by introducing a new class to maintain that.

public class HomePage extends AppiumBasePage {

}

public class LoginPage extends AppiumBasePage {
}

class Pages {

    AppiumBasePage login = new LoginPage();
    AppiumBasePage home = new HomePage();
}

It all depends on what you need to achieve.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...