使用泛型类作为类型参数

时间:2020-02-06 08:01:36

标签: java generics

我想使用一个通用类作为另一个通用类的类型参数。

起初,我的班级定义是这样的:

class Foo<T, R extends BaseDto> {}

然后,我的要求发生了变化,我不得不为R类型使用包装器/ holder类

到目前为止,我的尝试是:(给出编译时错误:类Bar<R>上的类或接口)

class Bar<T extends BaseDto> {
    private T dto;
    public Bar(T dto) {
        this.dto= dto;
    }
    // getters and setters
}
class Foo<T, Bar<R>> {
    private T entity;
    private R dto;
    // getters and setters
}

我不能将其用作Foo<T, Object>,因为使用此类的客户端将不知道他们实际上需要从ObjectBar的转换。

我将如何实现这种行为?

3 个答案:

答案 0 :(得分:3)

不要更改类头,而是将使用R的类中的所有位置替换为Bar<R>

因此类头保持不变:

class Foo<T, R extends CustomClass> 

但是,假设您有一个R类型的字段。需要更改为Bar<R>

Bar<R> someField;

答案 1 :(得分:0)

您可能需要的是:

class Foo<T, R extends CustomClass, S extends Bar<R>>

答案 2 :(得分:0)

您将使用

class Foo<T extends CustomClass, R extends Bar<T>> {}

如果Bar是固定的,即,如果用户不需要扩展Bar的另一个类,那么您需要摆脱R并仅在内部使用Bar<T> Foo

相关问题