Java通用类从类型参数中排除集合 [英] Java Generic Class Exclude Collections from Type Parameter

查看:154
本文介绍了Java通用类从类型参数中排除集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一种正确的方法来实现我所寻找的逻辑,但我很好奇为什么以下不起作用。半小时搜索没有找到答案,但可能我没有正确地说出问题。

I've found a proper way to implement the logic I was looking for, but I'm curious as to why the following doesn't work. Half an hour searching yielded no answers but it is possible I'm not wording the question properly.

我想要做的是限制类型参数,使Collections不会被接受。虽然我可以测试参数类型,但我宁愿让IDE指出类不接受Collection作为类型参数。我知道关键字排除不存在,但我希望它有助于说明手头的问题。

What I wanted to do was limit the type parameter such that Collections would not be accepted. While I can test the parameter type, I'd rather have the IDE indicate that the Class doesn't accept a Collection as a type parameter. I'm aware that the keyword excludes doesn't exist but I hope it helps illustrate the question at hand.

public class Foo<K excludes Collection, V>
{
  //TODO: Carry out Collectionist operations
} 

有没有办法在Java中做到这一点?我认为这不是最佳实践,即使可能,但我想满足我的好奇心,努力扩大我对泛型的理解。

Is there any way to do this in Java? I presume this isn't a best practice, even if it is possible, but I'd like to satiate my curiosity in an effort to expand my understanding of Generics.

感谢您的时间和考虑!

推荐答案

排除某些类型是不可能的。由于Java类型接口的方式,我可以简单地汇总我自己的 Collection ,它们具有完全相同的操作,并且不会被排除。

Excluding certain types is not possible. Due to the way how Java types interfaces, I could simply roll up my own Collection that has the exact same operations, and it would not be excluded.

为了好奇,这是一个公平的问题,但我并没有意识到在编译时实现它的方法。您可以在 Foo 的构造函数中放置运行时检查。

Just for the sake of curiosity it is a fair question, I am not aware of a way of achieving it at compile time though. You can place a runtime check in Foo's constructor.

这篇关于Java通用类从类型参数中排除集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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