开发者

Java bounded generic constraints on fields

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

private &l开发者_如何学Ct;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.


<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.


Let's assume that you want to instantiate your map variable. Theoretically you will have to write something like this:

map = new HashMap<GenericClass1<String>,GenericClass2<String>>();

Ok. But now what does not make sense to me anymore is what arguments the put or get methods will accept/return? T? Uh... what is T? GenericClass1|2<String>? Again makes no sense, does it? After all I see no String in the map declaration. So I guess there is no really correct instantiation and usage of this generic variable.

Cheers!


Oh, how I have longed for something like:

private <T> Map<Class<T>, T> instanceCache;

public <T> T getInstanceOf(Class<T> clazz) {
    return instanceCache.get(clazz);
}

But as you mentioned, it's completely impossible in Java. The method declaration above is fine, but there's no way to declare the variable such that there's not a cast in the method. Simply add this to the growing list of things you hate about generics and move on.


You can use ? as following:

private List<? extends List> l = new ArrayList<List>();

I hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜