Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics - Type must be from Class T "or" extend S

I am developing a ComboBox (more for context than actual significance), and I would like to know if the "or" operator exists in Java generics. For now, the declaration looks something like that:

public class SComboBox<T extends ComboBoxItem> extends JPanel {

Where ComboBoxItem is an interface I created for items that can be used in the ComboBox. However, I'd also like to accept String as a type, which seems like a difficult task since:

  1. String is a final class so there's no way anyone could extend it.
  2. I am not sure if you can put either something like "|" (or) operator, or just outright specify an acceptable class. Since there is an "and" operator (<T extends A & B>) I imagined it would make sense to have the "or" (|) as well.

My question is essentially point 2. Can I, in generics, specify a class I want to accept and/or use something like a "|"? If not, is there any workaround or should I ditch the idea of using generics?

like image 819
CLR 123 Avatar asked Dec 15 '21 12:12

CLR 123


1 Answers

There is no "or" operator for generics, and for a simple reason.

The idea of stating the type at the beginning is to allow you to use methods from that type in your implementation of the class.

When you use the "and" operator (extends A & B), you know that whatever object is passed to you, you can access any of the A class's methods as well as any of the B class's method.

But what would happen if it was an "or"? Then you are passed an object that can either be a ComboBoxItem allowing you to use ComboBoxItem's methods, or it is just a string, which means you can't use any such methods. At compile time, you don't know which object you are passed, so there is no point in giving the type.

The "Or" is not helpful. If you are not using any method from the object, you may as well not use extends at all.


The real question here is what you are trying to do which can apply to strings as well as combo box items but not to anything else. It smells like a design issue.

like image 165
RealSkeptic Avatar answered Sep 29 '22 07:09

RealSkeptic