DEV Community

Discussion on: Is there vararg-like generics in Java?

Collapse
 
baenencalin profile image
Calin Baenen

Yes. But, just like varargs, I want the user to enter as many as needed.

Collapse
 
alainvanhout profile image
Alain Van Hout

The user can’t input actual types, so I don’t see how that could be done.

Thread Thread
 
baenencalin profile image
Calin Baenen

Well, aren't "Types" just classes? Even primitives TYPES are classes, too.

When you use a generic, doesn't it just send the reference of the class to the variable?

class Test<T> { // T is our generic.

    public Test(T value /* T is a reference to the class. */) {/* code... */}

}

Test<String> test = new Test<>(); // T in this instance is Test is a reference to String.
Enter fullscreen mode Exit fullscreen mode

?

Is this true, or no?

Thread Thread
 
alainvanhout profile image
Alain Van Hout

I'm talking about the actual user input, not the developer.

With regard to your example, in Java that variable will be an object of type Test, which at compile time will have verified to use the type String in all cases where T is used in the general definition of the class. So no, no reference of the class is sent to the variable.

Thread Thread
 
baenencalin profile image
Calin Baenen

What if I use String.class?

Thread Thread
 
alainvanhout profile image
Alain Van Hout

String.class is a object representing the String type. But that's not what is needed here.

Think of it like this: if you have a generic box, a banana box and an apple box, then you can't transform a generic box into a banana box by throwing a banana at it. The banana needs to conceptually be in the picture when the box its design is created.

Thread Thread
 
baenencalin profile image
Calin Baenen • Edited

Okay.

Thanks.
Cheers.