java - Get array class of generic type -


i have class 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 generic type of given class don't have pass same class constructor parameter. i'm trying achieve getting array class of clazz.

for example if t string then

clazz = string.class; arrayclazz = string[].class; 

i solved creating new instance of t[] , reading class. wanted know if there's better way or if there downsides method.

update

what i'm trying do: have generic dataprovider requests json server. use gson parse 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)         ...     } } 

you should type erasure, may prevent clean way of doing you're asking for. (generics can't here.)

the problem in java, generic type data used @ compile time ensure looks good... , java forgets entirely. types aren't compiled in in way you'd hope, they're gone.

because of that, approach (i think!) cleanest, if feels hacky. need instantiate 1 , use reflection it's type.


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -