Reputation: 5110
I have the following function
EDIT: Changed int to class Long
protected <T> ApiResponse<T> getApiResponse(Object obj, Class<T> clasx)
How can I pass List<Long>
class as the second argument?
Can I pass List<Long>.class
but that is not working?
Upvotes: 2
Views: 3167
Reputation:
You cannot pass int
into the List
.
Because the T
here should be extends from Object
.
Integer
is extended from Object
, but not int
.
Upvotes: 0
Reputation: 16545
Type erasure means that you can only pass List.class
.
From the linked documentation:
When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.
For instance,
Box<String>
is translated to typeBox
, which is called the raw type — a raw type is a generic class or interface name without any type arguments. This means that you can't find out what type of Object a generic class is using at runtime. The following operations are not possible:
public class MyClass<E> {
public static void myMethod(Object item) {
// Compiler error
if (item instanceof E) {
...
}
E item2 = new E(); // Compiler error
E[] iArray = new E[10]; // Compiler error
E obj = (E)new Object(); // Unchecked cast warning
}
}
The operations shown in bold are meaningless at runtime because the compiler removes all information about the actual type argument (represented by the type parameter
E
) at compile time.
Upvotes: 8