Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Class of list with generic eg: List<Number>::class

Tags:

I have a generically typed class Builder<T> that takes a constructor argument Class<T> so I can keep the type around. This is a class that I use a lot in java code so I don't want to change the signature. When I try to use the constructor like this:

Builder<List<Number>>(List<Number>::class)

I get an error: "Only classes are allowed on the left hand side of a class literal"

Any way to resolve this? I can't change the constructor for Builder, too many java classes rely upon it.

I understand the whole type erasure issue, I really just want to make the compiler happy.

like image 879
Jonathan Leitschuh Avatar asked May 03 '16 23:05

Jonathan Leitschuh


People also ask

How do I get a class instance of generic type T?

The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.

What does class <?> Mean in Java?

What Does Class Mean? A class — in the context of Java — is a template used to create objects and to define object data types and methods. Classes are categories, and objects are items within each category. All class objects should have the basic class properties.

What is generic type class?

A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.

What is the class of List string in Java?

The implementation classes of the List interface are ArrayList, LinkedList, Stack, and Vector. ArrayList and LinkedList are widely used in Java programming.


1 Answers

Due to generic type erasure List class has a single implementation for all its generic instantiations. You can only get a class corresponding to List<*> type, and thus create only Builder<List<*>>.

That builder instance is suitable for building a list of something. And again due to type erasure what that something is you can decide by yourself with the help of unchecked casts:

Builder(List::class.java) as Builder<List<Number>> Builder(List::class.java as Class<List<Number>>) 

Another approach is to create inline reified helper function:

inline fun <reified T : Any> Builder() = Builder(T::class.java) 

and use it the following way:

Builder<List<Number>>() 
like image 152
Ilya Avatar answered Sep 19 '22 07:09

Ilya