I am trying to implement parameterized class in Java with enum as a type parameter. Everything works fine, except, if you look at the code below, there is that anonymous class Car.Creator
with parameter K
. But of course, instead of K
, there should be CarObject<T>
, but it's not that easy. If I put CarObject<T>
in K
's place, then I got syntax error. Could someone explain if something like this is possible and maybe provide with some code sample.
public class CarObject<T extends Enum<T>>
{
public Map<T, String> values;
private Class<T> typeClass;
public CarObject(Class<T> clazz)
{
typeClass = clazz;
values = new EnumMap<T,String>(typeClass);
}
public static final Car.Creator<K> Creator = new Car.Creator<K>()
{
public K create()
{
return new K();
}
public K[] newArray(int size)
{
return new K[size];
}
}
}
I can give you an example from official Android documentation(look at the code in 'Class Overview') where this works perfectly fine. I think there is some magic going on under the hood in Android. I'm trying to do exactly the same thing - implement Parcelable interface. I just made up this example without implements Parcelable
and other stuff, because I though maybe it's just a syntax sugar :).
I'm no Android expert, but I'm pretty sure there's nothing magic about how this is happening in Android. I think you're just confused about the relationship between generic type arguments and statics.
Generic type arguments (like
T
in your example) belong to the instances of the class, not to the class itself.Static members (like
Creator
in your example) belong to the class itself, not to the instances of the class.The fact that
Creator
is an anonymous inner class implementing a generic interface is a bit of a red herring here. The issue is simply that, regardless of whatCreator
is, as long as it isstatic
, it can't access the typeT
.