Question

I am not quite sure how to phrase my question, so I am gonna give an example:

Take this map for example:

Map<Class<? extends DatabaseEntry>, Class<? extends IDecorator<? extends DatabaseEntry>>> map;

It maps for example MyClass that extends DatabaseEntry to its IDecorator<MyClass>. The problem with the above statement is, that it is too unspecific. I want more type-safety. Something like this:

Map<Class<T extends DatabaseEntry>, Class<? extends IDecorator<T>>> map;

Of course, T would differ from entry to entry, but what I want is that if I call:

map.get(MyClass.class);

the return type would be IDecorator<MyClass> instead of IDecorator<? extends DatabaseEntry>

Is there a simple solution to that?

Was it helpful?

Solution 2

As far as I know - no way to do that.
You cannot of course use T, T must be a part of a generic definition,
and cannot be in a standalone definition of a variable like that, this is what you have wildcards ( ? ) for.
Since your map is taking for key and value objects of Class
You cannot even solve this by simply extending the types of the key and value (as Class is final).

OTHER TIPS

As @zaske already pointed out in his answer, this doesn't seem to be possible.

Along the lines of what you're already thinking about, you could wrap up your Map in a class that provides generified get and put methods as the ones you want.

public class MapWrapper { 

    Map<Class<? extends DatabaseEntry>, Class<? extends IDecorator<? extends DatabaseEntry>>> map;
    public <T extends DatabaseEntry> Class<IDecorator<T>> put (Class<T> k, Class<IDecorator<T>> v){
        return (Class<IDecorator<T>>) map.put(k,v);
    }

    public <T extends DatabaseEntry> Class<IDecorator<T>> getObject(Class<T> k) {
        return (Class<IDecorator<T>>) map.get(k);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top