Reputation: 3473
I have a class with a generic type. import java.lang.reflect.Array;
public abstract class MyClass<T> {
private Class<T> clazz;
private Class<?> arrayClazz;
public MyClass() {
clazz = ClassUtils.getParameterizedClass(getClass());
arrayClazz = Array.newInstance(clazz, 0).getClass();
}
}
The Utils method reads the generic type of the given class so I don't have to pass the same class as a constructor parameter. What I'm trying to achieve is getting the array class of clazz.
For example if T
is String then
clazz = String.class;
arrayClazz = String[].class;
I currently solved it by creating a new instance of T[] and reading its class. I wanted to know if there's a better way or if there are any downsides with this method.
Update
What I'm trying to do: I have a generic DataProvider which requests JSON from a server. I use GSON to parse the response.
public abstract class DataProvider<T> {
private final Class<T> resourceClass;
private final Class arrayClass;
protected DataProvider() {
this.resourceRootPath = resourceRootPath;
this.resourceClass = ClassUtils.getParameterizedClass(getClass());
arrayClass = Array.newInstance(resourceClass, 0).getClass();
}
public void get(String id) {
...
T obj = gson.fromJson(response.body().charStream(), resourceClass)
...
}
public void list(String id) {
...
T[] objs = gson.fromJson(response.body().charStream(), arrayClass)
...
}
}
Upvotes: 5
Views: 2870
Reputation: 40298
You should look up Type Erasure, which may prevent a clean way of doing what you're asking for. (Generics can't help you here.)
The problem is that in Java, generic type data is used at compile time to ensure everything looks good... and then Java forgets about it entirely. The types aren't compiled in in the way you'd hope, they're just gone.
Because of that, your approach is (I think!) the cleanest, even if it feels hacky. You need to instantiate one and use reflection to get it's type.
Upvotes: 3