0

I am using dependency injection to inject an implementation of an interface. I would like to make it possible to call a method on the injected type with a parameter whose implementation is also being injected and based on an Interface.
Example:

  • SessionInterface is implemented by Session_A and Session_B
  • ConfigInterface is implemented by Config_A and Config_B
  • Session_A should only use objects of Config_A, same with _B

In the application an implementation of a session is injected (without a config). Later, an implementation of config can be injected, to use it as a parameter for the session's method run(ConfigInterface config)
In this method I'd like to make sure that the given parameter's type is the one corresponding to the session.

Should I use getClass(), instanceof or something else to check this?

nmnd
  • 105
  • 12
  • In your sessionInterface you can define template like and then in implementation class of Session_A you can directly use Config_A in run method and you wont even need to use instanceof or getclass(). Otherwise instanceof is better – ygbgames Jan 23 '19 at 17:57

1 Answers1

0

(You'll find a lot of discussion in this problem space. I'm still improving my understanding of this type of problem, and I welcome any improvements to this answer.)

One possible answer is to use a PECS type pattern (PECS stands for Producer Extends and Consumer Super; see What is PECS (Producer Extends Consumer Super)?).

Here is a code example:

interface PECS_Supplier<T> {
    T supply();
}

interface PECS_Consumer<T> {
    void consume(T value);
}

public class PECS_Engine {
    public <T> void process(PECS_Supplier<? extends T> supplier, PECS_Consumer<? super T> consumer) {
        T nextValue;
        while ( (nextValue = supplier.supply()) != null )  {
            consumer.consume(nextValue);
        }
    }
}

Note the "? extends T" and "? super T" in the process method.

Thomas Bitonti
  • 1,179
  • 7
  • 14