Let's say I have a pool of adapter classes. All of them are concretions of a generic interface, such as:

interface Adapter<Target,Source> {
    Target adapt(Source object);

Now, my idea was to implement such a pool as a map in which keys are target and source classes:

final DoubleKeyMap<Class<?>, Class<?>, Adapter<Class<?>,Class<?>>> adapters;

And clients can ask the pool for the appropriate adapter in this manner:

(Adapter<Target, Source>) adapters.get(targetClass, sourceClass);

However, I'm not sure this is the 'best' way of accomplishing it.

  • \$\begingroup\$ Just a thought.. How about you create a wrapper which has Target and Source's Class instances and you use that Wrapper as key in regular HashMap ?? class Wrapper { Class<Target> target; Class<Source> source;} \$\endgroup\$ – Tiny Rick Oct 20 '17 at 6:14
  • \$\begingroup\$ I had considered it, but for such as wrappers to act as keys, I'd had to force clients (users of the pool) to be aware of a multitude of interfaces - at least each one for each combination of target and source types. \$\endgroup\$ – AmazingWouldBeGreatBut Oct 20 '17 at 12:25

Your clients do not need about how you are providing the Adapter<>. They just have to provider the Target and Source class instances.

Here is one possible implementation,

public class DoubleKeyMap {

    private Map<Wrapper, Adapter<Target,Source>> adapterMap;

    public DoubleKeyMap(Map<Wrapper, Adapter<Target,Source>> adapterMap) {
        this.adapterMap = adapterMap;

    public Adapter<Target,Source> get(Class<Target> targetClass, Class<Source> sourceClass) {

        Wrapper wrapper = new Wrapper(targetClass, sourceClass);

        return adapterMap.get(wrapper);

    private class Wrapper {

        private Class<Target> target;

        private Class<Source> source;

        private Wrapper(Class<Target> target, Class<Source> source) {
            this.target = target;
            this.source = source;

Hide the wrapper from outside world by making it private.

The client just provide Target and Source Class instances

class Client {
    public static void main(String[] args) throws ClassNotFoundException {
        DoubleKeyMap doubleKeyMap = new DoubleKeyMap(Collections.emptyMap());

        Adapter<Target, Source> targetSourceAdapter = doubleKeyMap.get(Target.class, Source.class);
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.