Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

generics question, type mismatch

 
Denis Wen
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • 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
 
Henry Wong
author
Marshal
Pie
Posts: 20907
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • 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
 
Rob Spoor
Sheriff
Pie
Posts: 20497
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • 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>.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic