但是你也可以使用通用的构造函数,这意味着构造函数显式接收自己的泛型类型参数,例如: ; U>酒吧(你){ //为什么!? } }
我在努力理解用例。这个功能让我做什么?
解决方案
这个功能让我能做什么?
至少有三件事可以让你做,否则你无法做:
表示参数类型之间的关系,例如:
class Bar {< T> Bar(T对象,Class< T>类型){ //'type'必须表示'object'可赋值的类, //尽管不一定是'object'的精确类。 // ... } }
< withdrawn>
As everyone knows you can have a generic class in Java by using type arguments:
class Foo<T> { T tee; Foo(T tee) { this.tee = tee; } }But you can also have generic constructors, meaning constructors that explicitly receive their own generic type arguments, for example:
class Bar { <U> Bar(U you) { // Why!? } }I'm struggling to understand the use case. What does this feature let me do?
解决方案What does this feature let me do?
There are at least three two things it lets you do that you could not otherwise do:
express relationships between the types of the arguments, for example:
class Bar { <T> Bar(T object, Class<T> type) { // 'type' must represent a class to which 'object' is assignable, // albeit not necessarily 'object''s exact class. // ... } }<withdrawn>
As @Lino observed first, it lets you express that arguments must be compatible with a combination of two or more unrelated types (which can make sense when all but at most one are interface types). See Lino's answer for an example.
更多推荐
泛型构造函数在Java中的用途是什么?
发布评论