• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

generics question, type mismatch

 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
His,

I am having this error "Type mismatch: cannot convert from Class<capture#3-of ? extends Object> to Class<V>". Everything looks fine to me, shouldn't value.getClass() return variable of type Class<V>?

public abstract class NotifyCache<K,V> implements Cache<K,V> {
protected void notifyPut(K key, V value) {
Class<V> clazz = value.getClass(); //error here
//doing stuff....
}
}

thanks
 
author
Posts: 23959
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Everything looks fine to me, shouldn't value.getClass() return variable of type Class<V>?



Yeah. You would think that it would be the case? But it's not.

The getClass() method is from the Object class. And the Object class is not a generic class. So, the getClass() method returns a Class object of an unknown type (? that extends Object, to be exact).

IMO, I think they purposely didn't make the Object support generics, and the reason is because it would be too annoying to fix everything -- since everything inherits from the Object class.

Henry
 
Sheriff
Posts: 22849
132
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You know that value is an instance of V, but you can't know the exact class.

If V is a class, value can be of a sub class of V. For instance, if V is Number, then value.getClass() will return Integer.class (which is a Class<Integer> object) if value is actually an Integer object.

If V is an interface however, value can be of any class as long as it implements V. This is why value.getClass() does not even return a Class<? extends V>.
 
reply
    Bookmark Topic Watch Topic
  • New Topic