Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Main method with generic parameter; why does it work?

public static <T extends String> void main(T[] args) {     System.out.println("Hello World!"); } 

I was curious to see if the above snippet of code would compile and run successfully, and it does! However, I also wondered what would happen if T extends String was replaced with T extends String & AutoClosable; String does not implement AutoClosable, so I didn't expect this to run successfully, but it still does!

public static <T extends String & AutoCloseable> void main(T[] args) {     System.out.println("This still works!"); } 

So my question is, why does this still run successfully?

Notes:

  • I'm testing this with Java 10.0.1
  • Intellij doesn't play nice with this method because it doesn't see it as an entry point to the program; I haven't tested it with other IDEs.
  • You're also able to pass arguments using the command-line just as you would with any other program.
like image 785
Jacob G. Avatar asked Jul 15 '18 20:07

Jacob G.


People also ask

How do generic methods work?

Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. If there isn't such a dependency, a generic method should not be used. It is possible to use both generic methods and wildcards in tandem.

Why do we use generic method?

In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.

Why do we use generics for getting a list of multiple elements?

Advantage of Java Generics 1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store other objects. Without Generics, we can store any type of objects. List list = new ArrayList();

How does generics work in Java?

Generics enable the use of stronger type-checking, the elimination of casts, and the ability to develop generic algorithms. Without generics, many of the features that we use in Java today would not be possible.


1 Answers

This is because a type parameter has a bound:

<T extends String>                  =>  String  <T extends String & AutoCloseable>  =>  String & AutoCloseable 

And the bytecode after erasure is the same as for the regular main declaration in both cases:

public static main([Ljava/lang/String;)V 

JLS §4.4. Type Variables:

The order of types in a bound is only significant in that the erasure of a type variable is determined by the first type in its bound, and that a class type or type variable may only appear in the first position.

like image 95
Oleksandr Pyrohov Avatar answered Sep 29 '22 06:09

Oleksandr Pyrohov