0

I have an application class "Application", one abstract class "AbstractClass" extended by "Impl1" and "Impl2". The application class gets the impl1 or impl2 to perform some task based on the input it receives.

Currently I am injecting both the classes into the application class as shown below. Then based on input, I either ask impl1 OR impl2 to perform the task.

public class Application {

         private static final Data data1 = DATA_CONFIG.data_1;
         private final AbstractClass impl1;
         private final AbstractClass impl2;

         @Inject
         Application(final AbstractClass impl1, final AbstractClass impl2){
               this.impl1 = impl1;
               this.impl2 = impl2;
         }

         public void mainTask(final Data data){

               if(data == data1){
                    impl1.performTask();
               }else{
                    impl2.performTask();
               }
         }
}

But, is there any way I could use assisted inject or a similar concept to inject only the dependency required, so for example input is data1, I only inject impl1 and not impl2.??

1 Answers1

0

So, what you want is to select injected object depending to some context of injection point - value of Data object in particular. I didn't do such things and can't guarantee success, but you can try custom injections.

Also you can do something like factory. But IMHO, this approach is not much better than original, cause it will just move selection between impl1 and impl2 to a factory class you have to create first.

Sketch:

@Inject
Application(IAbstractClassFactory factory){
    this.factory = factory
}

void mainTask(final Data data){
    impl = factory.create(data)
}
I.G.
  • 370
  • 1
  • 8