简体   繁体   中英

Can I make the compiler ignore bound mismatch error? (Or fix this instance of it)

I have a method (that I can't change, it belongs to a different project) defined in an interface that limits the input classes using generics to a Class that extends a Class (which in turn implements an interface), like this:

<P extends ParentInterface, E extends P> void register(Class<E> cl, Class<P> parent);

This works fine when you're calling it normally, but in order to make it easier to register a potentially large number of classes this way (and unregister the same set when needed) I was hoping to store them in a Map<Class<? extends ParentInterface>, Class<? extends ParentInterface>> Map<Class<? extends ParentInterface>, Class<? extends ParentInterface>> Map<Class<? extends ParentInterface>, Class<? extends ParentInterface>> (or similar) and loop over it when registering/unregistering. Unfortunately this - predictably - leads to compile time errors saying bound mismatch:

Bound mismatch: The generic method register(Class<E>, Class<P>) is not applicable for the arguments (Class<capture#5-of ? extends ParentInterface, Class<capture#13-of ? extends ParentInterface>). The inferred type capture#5-of ? extends ParentInterface is not a valid substitute for the bounded parameter <E extends P>

Can I get around this in some way, or am I stuck doing individual calls and making sure I'm keeping the register and unregister calls synchronized?

does it help to make the class generic, that will EDIT not encapsulate but extends the Map interface?

public class TestMap <P extends ParentInterface, E extends P> extends HashMap implements Map {
    void registerall(){
        Class<E> key = (Class<E>) this.keySet().iterator().next();
        Class<P> val = (Class<P>) this.get(key);
        register(key, val);
    }

}

When (un)registering simply make use of wildcard capture and asSubclass(Class) :

Class<? extends ParentInterface> parent = entry.getValue();
Class<? extends ParentInterface> child = entry.getKey();
registerWithCapturedParent(parent, child);

private <P extends ParentInterface> void registerWithCapturedParent(Class<P> parent,
    Class<? extends ParentInterface> child) {
    Class<? extends P> boundedChild = child.asSubclass(parent);
    registry.register(boundedChild, parent);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM