Java Generic Class Exclude Collections from a Type Parameter

I found the right way to implement the logic I was looking for, but I am curious why the following does not work. A half-hour search did not answer, but perhaps I am not correctly formulating the question.

What I wanted to do was to restrict the type parameter so that collections would not be accepted. Although I can check the type of the parameter, I would prefer the IDE to indicate that the class does not accept the collection as a type parameter. I know that the keyword excludes does not exist, but I hope this helps to illustrate this issue.

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

Is there any way to do this in Java? I believe that this is not the best practice, even if it is possible, but I would like to satiate my curiosity, trying to expand my understanding of generics.

Thank you for your time and attention!

+5
source share
2 answers

Exclusion of certain types is not possible. Due to the way Java interfaces interact, I could just collapse my own Collection , which has the same operations, and it will not be excluded.

Just for the sake of curiosity, this is a fair question, but I don’t know how to achieve it at compile time. You can put the execution check in the Foo constructor.

+1
source

It is impossible to implement.

The current version of generics only supports extends or super. It does not support any negative scenario.

+2
source

Source: https://habr.com/ru/post/1200609/


All Articles