Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java bounded generic constraints on fields

Tags:

java

generics

There have been a couple of times when I've felt the need to do something like the following:

private <T extends Type> Map<GenericClass1<T>,GenericClass2<T>> map;

...or something to that effect. Essentially, using an identical bound in the two arguments for map. (This isn't an actual example, just shows the idea.)

I know this (unfortunately) isn't possible and that it's only available on class definitions and method signatures. My question however is why isn't it available on fields? Is it purely a design choice or is there some technical reason behind it that I'm missing? I've had a think and can't see why this shouldn't be possible from a technical perspective, as far as I can see everything is there for the compiler to work it out correctly and none of the generic information is required at runtime.

like image 980
Michael Berry Avatar asked Oct 14 '22 17:10

Michael Berry


1 Answers

<T> means ONE class, not A class. When your object is instanced T is bound to this ONE class.

You are trying to put two objects with diffrent interfaces (used diffrently because they take/return diffrent types) in to the same container. This is a error because when you take them out of the container (the map) you dont know what it was you put in.

Hope this is the answer you were looking for.

Edit: That said you can have a container that holds members based on there class, to automatically create a new map for EACH type of T. You would then need to know what T was in order to access it. In general, if you dont want the type information anymore, throw it away. If you do then putting it in the same container as something of another type will throw it away anyway for all practical reasons.

like image 53
mncl Avatar answered Nov 17 '22 09:11

mncl