Java: Get Class<T> object of generic class -


this question has answer here:

i have generic class

public myobject<t extends someclass1, s extends someclass2> extends someexternalclass {     // ....     @override     public void somefunction() {         externalclass.dosomething(t.class); // problem here!     } } 

inside class, need object of type class<t> pass function of external library. external library expects object of type class<t extends someclass1>as parameter.

i read solution pass class<t> constructor of object. unfortunately, myobject extends class, external library, has constructor called - no option me.

i read guava, example here: get generic type of class @ runtime difference problem need object of type class<t> , not object of type type. how can achieve this?

thanks in advance!

as mentioned pshemo in comment can't in java directly because of type erasure. however, couple of ways achieve take class parameter of somefunction. e.g.

public class myobject<t extends someclass1, s extends someclass2> {     // ....     public void somefunction(class<t> clazz) {         externalclass.dosomething(clazz); // problem here!     } } 

then push problem further out.

in case have field of type t has object of type use pass externalclass, e.g.

public class myobject<t extends someclass1, s extends someclass2> {     private t t;     public myobject(t t) {         this.t = t;     }      public void somefunction() {         externalclass.dosomething(t.getclass()); // problem here!     } } 

a third option if can not alter signature of neither constructor nor somefunction maldate call setter method control, e.g.

public class myobject<t extends someclass1, s extends someclass2> {     private t t;      public void somefunction() {         externalclass.dosomething(t.getclass()); // problem here!     }      public void setclazz(t t) {         this.t = t;     } } 

you expand on , let caller register callback use resolve class, might overkill...


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -