Announcement Announcement Module
No announcement yet.
OT question on Java Generics Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • OT question on Java Generics

    Hi all,

    first of all I apologize for submitting a problem that is not directly related to Spring but to Java. My only excuse is that there are a lot of highly experienced Java gurus in the forum, and I have not been able to google up for a solution for days now.

    I have a method that will return a Map<K,V>. The actual Map class shall be passed as parameter to the method, such as here:

    	public <K,V,T extends Map<K, V>> T loadMap(Class<T> clazz);
    This looks fine, and even compiles without problems. However I have not found a way to call that method without either receiving an unchecked conversion warning, or I need to add the @SuppressWarnings("unchecked") annotation (which I do not want).

    I tried

    	// works but gives a warning
    	Map<String, Long> myMap = loadMap(HashMap.class);
    	// obviously gives a compiler error
    	Map<String, Long> myMap = loadMap(HashMap<String, Long>.class);
    	// doesn't work either
    	Map<String, Long> myMap = loadMap(Class<HahMap<String.Long>>);
    Has anyone got a picture on how to correctly spell a class parameter using generics?

    Thanks for any pointer, and even for a "no way" if you're quite sure about that ;-)

    And sorry again for the OT question.


  • #2
    hmmm.. it's my understanding that class literals are one of the exceptions where you have to use raw types (the other being instanceof).

    See Joshua Bloch's Effective Java (2nd edition) item #23 at the end. At least that's my interpretation of what he's saying.

    So I *believe* you have to go with your first option and suppress the warnings?


    • #3
      Thanks for answering and - unfortunately - confirming my expectations... meanwhile I've found another good explanation that may help others:

      Best regards, Ernest