I have a bit tricky situation, where the main class(class A) injects a dependency(class B), and then inside one of the methods of class A it delegates calls to class B.
So far, this doesn't sound tricky at all, but here is the twist: as class B is injected into class A automatically, it doesn't get the required argument to construct itself properly. Let me show you what I'm talking about:
class A {
@Inject // inject object B
public A(B objectB) {
this.objectB = objectB
}
// delegate call to object B, however param1 is required in class B constructor in order to be constructed correctly
public void example_method(String param1) {
this.objectB.someMethod();
}
}
class B {
private C objectC;
// class B needs param1 in order to create object C, so param1 has to be passed at the creation time
public B(String param1) {
objectC = new C(param1);
}
public void someMethod() {
objectC.someOtherMethod();
}
public void someMethod2() {
objectC.someOtherMethod2();
}
}
I hope you can see the issue here: because class B is injected into class A by Guice, it doesn't have access to the param1
which only gets passed to one of the class A methods. In a sense, class B is created prematurely without the required data.
Is there a way to construct the code so that the construction of class B is delayed after example_method() of class A has been called ? If that's not possible, how would you refactor this, having in mind that I need to construct class C directly in class B's constructor, as it's going to be called from many different methods inside class B.