泛型构造函数在Java中的用途是什么? [英] What purpose do generic constructors serve in Java?

查看:320
本文介绍了泛型构造函数在Java中的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class Foo< T>所有人都知道您可以在Java中使用泛型类。 {
T tee;
Foo(T tee){
this.tee = tee;


但是你也可以使用通用的构造函数,这意味着构造函数显式接收自己的泛型类型参数,例如: ; U>酒吧(你){
//为什么!?
}
}

我在努力理解用例。这个功能让我做什么?

解决方案


这个功能让我能做什么?


至少有三件事可以让你做,否则你无法做:


  1. 表示参数类型之间的关系,例如:

      class Bar {
    < T> Bar(T对象,Class< T>类型){
    //'type'必须表示'object'可赋值的类,
    //尽管不一定是'object'的精确类。
    // ...
    }
    }


  2. < withdrawn>

  3. 由于@Lino首先观察到,它可以让你表达参数必须与两个或更多不相关类型的组合兼容(可以当最多只有一个是接口类型时才有意义)。查看Lino的答案举例。


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:

  1. 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.
            // ...
        }
    }
    

  2. <withdrawn>

  3. 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中的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆