Results 1 to 3 of 3

Thread: OT question on Java Generics

  1. #1
    Join Date
    Nov 2009
    Posts
    6

    Thumbs up 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:

    Code:
    	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

    Code:
    	// 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.

    Regards,
    Ernest

  2. #2
    Join Date
    Mar 2010
    Posts
    12

    Default

    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. #3
    Join Date
    Nov 2009
    Posts
    6

    Red face

    Thanks for answering and - unfortunately - confirming my expectations... meanwhile I've found another good explanation that may help others: http://stackoverflow.com/questions/2...a-generic-type

    Best regards, Ernest

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •