Question

Possible Duplicate:
Java Generics, how to avoid unchecked assignment warning when using class hierarchy?

Intellij is giving me the warning below. Not sure how to resolve it, or even if I need to resolve it. The warning details says it only applies to JDK 5, and I am using 6. I am wondering if I need to respond to this, and if so, how?

Method call causing warning

List<T> refObject = cache.getCachedRefObject(cacheKey, List.class);

Method being called

public  <T> T getCachedRefObject(String objectKey, Class<T> type) {
    return type.cast(refObjectCache.get(objectKey));
}

Warning details

Unchecked Assignment
JDK 5.0 only. Signals places where an unchecked warning is issued by the compiler, for example:
    void f(HashMap map) {
        map.put("key", "value");
    }
Was it helpful?

Solution

Having played with super type tokens for this, I don't think you can make this type-safe without making extra methods to retrieve collections from your cache and verifying if their contents are of the correct type.

Your options are:

  1. Doing the above, which seems laborious
  2. Suppress the unchecked cast in client code if you know it's correct.
  3. Replace the client code with List<?> refObject = cache.getCachedRefObject(cacheKey, List.class);

The only type-safe variant of these is 3., in that it prevents you from doing operations that the compiler can't prove are type-safe. The obvious downside is that you might want to do some of these operations anyway.

OTHER TIPS

Sounds like you have an old version of IntelliJ. This warning really means Java 5.0+ and AFAIK this was changed when IntelliJ supported Java 6 so the warning was there but didn't say "JDK 5.0 only" (it now has support for Java 8)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top