Generic lower bound to Object

2020-07-22 19:05发布

It is possible to code a generic parameter bound as:

public <T super Object> void someMethod(T t);

Is there a valid usage of such a bound?

标签: java generics
2条回答
祖国的老花朵
2楼-- · 2020-07-22 19:28

According to the JLS http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.4 a type parameter (The < T extends Object > term) consists out of:

TypeParameter:
    TypeVariable TypeBound*

TypeBound:
    extends TypeVariable
    extends ClassOrInterfaceType AdditionalBoundList*

AdditionalBoundList:
    AdditionalBound AdditionalBoundList
    AdditionalBound

AdditionalBound:
    & InterfaceType

* = optional

You see the TypeBound, there is only the usage of extends specified. Unfortunately, a lower bound type parameter, using super, is not specified. A lower bound is only specified in the wildcard usage (JLS#4.5.1)

Good question, that got me digging in the JLS, and I don't know why this not implemented in java, it is just not specified.

查看更多
Luminary・发光体
3楼-- · 2020-07-22 19:40

Such a lower bond is totally useless. If you want to have a template that can only accept the Object, all you have to do is to remove all the generic template and code directly your class using the Object as your type.

For other types than Object, it doesn't make any sense neither. Why would you want of a template that would accept object of type A or objects without the type A (Object for example) but that would refuse object of type B when B is a subclass of A? It's totally illogical.

Same thinking with the interface: you would accept any types that don't implement an interface I at all or that implement it but you would refuse a type that not only have the interface I but have extended it???

查看更多
登录 后发表回答