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)
...
}
}