Reputation: 1157
I want to load a generic list. Therefore I want to use a function like :
public static <T> List<T> load()
{
FileInputStream fileStream = null;
List<T> toReturn = new ArrayList<T>();
String fileExtension = toReturn.getClass().getComponentType().getSimpleName();
...
}
if you can see I want to get the Type ("T"), to search for files with these extensions. But if I call :
StorageUtil.<MyClass>load();
I get an Exception instead of getting "MyClass" as fileExtension. What's wrong on my code?
Upvotes: 1
Views: 569
Reputation: 1503459
The problem is that generics in Java don't work that way - you can't find the type of T
at execution time due to type erasure. If you need the type at execution time, you can add a Class<T>
parameter:
public static <T> List<T> load(Class<T> clazz) {
... use class.newInstance() to create a new instance, etc
}
See the Java Generics FAQ entry for Type Erasure for more information.
Upvotes: 8