Java泛型,其返回类型具有@NonNull和Collections [英] Java generic with return type that has @NonNull with Collections

查看:296
本文介绍了Java泛型,其返回类型具有@NonNull和Collections的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Java8中实现一个泛型函数,该函数验证集合没有空成员并返回带有@NonNull批注的类型.

I want to implement a generic function in Java8, that verifies that a collection has no null members and returns a type with @NonNull annotation.

输入类型:T扩展Collection,其中T + U可为空.
结果类型:@NonNull T,带有@NonNull U

input type: T extends Collection, where T+U are nullable.
result type: @NonNull T, with @NonNull U

对于数组,它看起来像这样:

For array this would look like this:

public static <T> @NonNull T @NonNull[] arrayHasNoNullMember( @Nullable T @Nullable[] value) {

但是对于集合的情况,我不知道如何定义结果类型与输入类型相同,但是对于集合和元素类型具有@NonNull批注.
这是我想做的,但是它不是有效的语法:

But for the collection case, i don't know how to define that the result type is the same as the input type, but has the @NonNull annotations for the collection and the element type.
This is what i want to do, but it is not valid syntax:

public static <T extends Collection<U>, U> @NonNull T<@NonNull U> collectionHasNoNullMember(T<U> col) {

你能帮忙吗?

推荐答案

不幸的是,Java中无法更改通用类型的通用类型参数,例如T extends Collection<U>中的U.与您的array方法等效的方法是采用并返回Collection实例的方法,如下所示:

Unfortunately there's no way in Java to alter a generic type parameter of a generic type, like the U in T extends Collection<U>. The equivalent of your array method would be a method that takes and returns Collection instances, like so:

public static <E> @NonNull Collection<@NonNull E> collectionHasNoNullMember(@Nullable Collection<? extends @Nullable E> col)

这可以接受Collection的任何子类,但是返回类型不能比Collection更具体.

This accepts any subclass of Collection, but the return type can't be more specific than Collection.

要处理更具体的情况,我建议为通用子类提供更多方法:

To handle more specific cases, I would suggest having a few more methods for common subclasses:

public static <E> @NonNull List<@NonNull E> listHasNoNullMember(@Nullable List<? extends @Nullable E> list)
public static <E> @NonNull Set<@NonNull E> setHasNoNullMember(@Nullable Set<? extends @Nullable E> set)
public static <E> @NonNull Queue<@NonNull E> queueHasNoNullMember(@Nullable Queue<? extends @Nullable E> queue)

或者,只要您返回相同的对象,就可以始终手动将其强制转换回其实际类:

Or, as long as you're returning the same object, you can always manually cast it back to its actual class:

ArrayList<@NonNull E> list2 = (ArrayList<@NonNull E>) collectionHasNoNullMember(arrayList);

这篇关于Java泛型,其返回类型具有@NonNull和Collections的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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