Reputation: 4767
I have next code:
class iCache<K,V> implements Map<Object, Object>
{
...//Code
}
How can I get the class name of K and V?
Upvotes: 3
Views: 112
Reputation: 26882
If you extend iCache
and want to obtain the typer parameters you used to declare the subclass (like below):
class someCache extends iCache<Integer,Long> {
//...
}
You can find out those parameters at runtime using the following (source):
Class clazz = ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
If you provide the parameters at instantiating like this
iCache<Integer,Long> cache = new iCache<Integer,Long>();
then you are out of luck (more info).
Upvotes: 3
Reputation: 634
Actually you can, call the getClass() method on the key and value
Upvotes: 0
Reputation: 22741
The types will get erased. Pass in Class and Class as args into the constructor to pass through your raw types. Store as fields. Note: your patameterisation is bad anyway: you need to pass K and V to Map as well, or you'll give yourself more pain.
Upvotes: 2
Reputation: 272772
You can't. Java generics don't work that way. At runtime, there is no class-specific information available (this is known as erasure
). If you really need this information, you will have to pass in e.g. Class
objects.
Upvotes: 5
Reputation: 13817
You can't, the compiler performs type erasure at compile time. In other words, the K and V type parameters are purely a compile time notion, they aren't accessible at runtime.
What you can do is to grab the class of the key/values in your custom Map type at runtime.
Upvotes: 7