5

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");
    }
Community
  • 1
  • 1
EdgeCase
  • 4,719
  • 16
  • 45
  • 73
  • 1
    I don't think you can resolve the cast in this case - you can't reify `List` using a `Class` as a type token. – millimoose Sep 24 '12 at 14:12
  • @Nambari This has nothing to do with the get-put principle. The cast is unchecked because of the raw type. – millimoose Sep 24 '12 at 14:15

2 Answers2

3

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)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

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.

millimoose
  • 39,073
  • 9
  • 82
  • 134