1

I have this static factory method:

   public static CacheEvent getCacheEvent(Category category) {
        switch (category) {
            case Category1:
                return new Category1Event();
            default:
                throw new IllegalArgumentException("category!");
        }
    }

Where Category1Event is defined as;

class Category1Event implements CacheEvent<Integer> ...

My client code for above static factory method looks like:

   CacheEvent c1 = getCacheEvent(cat1);

EDIT: The above code works fine. However I prefer that I don't use raw type CacheEvent and rather use the parameterized type. An obvious disadvantage of using the raw type above is, I will have to cast in following cases:

   Integer v = c1.getValue(); // ERROR: Incompatible types, Required String, Found Object. 

I can do an unchecked assignment as follows, but this gives a warning. I am trying to avoid if it is possible.

// Warning: Unchecked Assignment of CacheEvent to CacheEvent<Integer>. 
CacheEvent<Integer> c1 = getCacheEvent(cat1);

Asad Iqbal
  • 3,241
  • 4
  • 32
  • 52

1 Answers1

2

You can do this:

// Notice the <T> before the return type
// Add the type so the type for T will be determined
public static <T> CacheEvent<T> getCacheEvent(Category category, Class<T> type) {
    switch (category) {
        case Category1:
            return (CacheEvent<T>) new Category1Event(); // Casting happens here
        default:
            throw new IllegalArgumentException("Category: " + category);
    }
}

With that, type parameter T will be assigned with the correct class when returning the matching instance type that factory returns.

CacheEvent<Integer> cacheEvent = getCacheEvent(integerCategory, Integer.class);
int value = cacheEvent.getValue(); // no warnings!
sweet suman
  • 1,031
  • 8
  • 18
  • Thanks @KaNa0011, I actually wrote that code but then realized that I need the unchecked cast within the getCacheEvent method. So there doesn't seem to be any way around this problem without unchecked casts? – Asad Iqbal Jan 30 '19 at 16:02