简体   繁体   English

如何指示泛型类从一个或另一个类扩展?

[英]How can I indicate that a generic class extends from one class or another?

Hi I have the next class 嗨,我下一堂课

public class ApiResponse<T extends ApiResponseData > 

When T is a type of the ApiResponseData , but sometimes I receive to a list instead of an object and for this case I need the T to be extended from ApiResponseData or List<ApiResponseData> how can do it this? TApiResponseData的类型时,但有时我收到的是列表而不是对象,对于这种情况,我需要从ApiResponseDataList<ApiResponseData>扩展T怎么做?

My attempt 我的尝试

public class ApiResponse<T extends ApiResponseData || T extends List<ApiResponseData>> 

I think you have a fundamental misunderstanding of the purpose of generic type parameters. 我认为您对通用类型参数的用途有基本的误解。 Why do you think you need the type parameter to change to accommodate lists? 您为什么认为需要更改type参数以容纳列表?

Why is something like this not sufficient? 为什么这样的东西还不够?

class ApiResponse<T extends ApiResponseData>
{
    final List<T> data;

    ApiResponse(T datum)
    {
        data = Collections.singletonList(datum);
    }

    ApiResponse(List<T> data)
    {
        this.data = data;
    }
}

您可以等待public class ApiResponse<T extends List<ApiResponseData> >并在调用此方法时将T extends ApiResponseData情况视为一个元素的列表(在代码中较高)

It is not possible as because it will be ambiguous for java to decide which class to use during type erasing. 这是不可能的,因为java决定在类型擦除期间使用哪个类是不明确的。 You can use Generic to specify the constraint like T needs to be a subclass of multiple class like (A & B) like <T extends A & B> but your use case not possible. 您可以使用泛型来指定约束,例如T需要像(A&B)这样的多个类的子类,例如<T extends A & B>但是您的用例是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM