简体   繁体   中英

How to avoid an unchecked cast with java and generics in strategy pattern

I have a coding pattern in java which is some flavor of the strategy pattern. My problem is that the code requires an unchecked cast which I would like to avoid. To explain it briefly, I firstly have a set of classes which share a common interface:

interface IType {}

class TypeA implements IType {}
class TypeB implements IType {}

Then I have a set of strategies which do some specific processing on IType objects.

interface IStrategy<T extends IType> {
    specificProcessing(T o);
}

Lastly, I have a singleton which does some generic processing on ITypes, then fetches the proper IStrategy to do the specific processing. The IStrategy objects are registered in map and I think the method signature ensures that only matching pairs of ITypes and IStrategies go into the map.

class Context {

    private Map<Class<? extends IType>, IStrategy<? extends IType>> map;

    public static Context getInstance() {}

    public <T extends IType> void register(IStrategy<T> s, Class<T> c) {
        map.put(c, s);
    }

    public <T extends IType> void genericProcessing(T o) {
        //do generic stuff with o
        @SuppressWarnings("unchecked") 
        IStrategy<T> s = (IStrategy<T>) map.get(o.getClass());
        s.specificProcessing(o);
    }

}

The "problem" is the unchecked cast warning. I know this happens because the declaration of the map allows non-matching pairs of IType and IStrategy. I also know that the code is type safe because of register(). But is there any other design which avoids the unchecked cast?

I would appreciate any input, thanks.

There is no way to avoid it when using this map. I would suggest moving the map access into a separate method, so the code reads more cleanly.

@SuppressWarnings("unchecked")
private <T extends IType> IStrategy<T> getStrategy(T o) {
    return (IStrategy<T>) map.get(o.getClass());
}

BTW, you can do it in scala.

Edit:

You can do it in Octarine , see blog on post Extractors . But maybe this is just a fancy way or moving the logic to it's own method, but bringing in a lot of complexity.

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