How can I determine if Java generic implements a particular interface? -
how can determine if java generic implements particular interface?
i have tried few different approaches, results in "cannot find symbol ... variable t" error.
first attempt
public abstract class abstractclass<t> { public void dofoo() { if (t instanceof someinterface){ // stuff } } }
second attempt
public abstract class abstractclass<t> { public void dofoo() { if (someinterface.class.isassignablefrom(t)) { // stuff } } }
workaround 1
add constructor taking class of object.
public abstract class abstractclass<t> { private class<t> clazz; public abstractclass(class<t> clazz) { this.clazz = clazz; } public void dofoo() { if (clazz instanceof someinterface){ // stuff } } }
workaround 2
add constraint type t
t extends someinterface
, thereby restricting type t
subtype of someinterface
.
public abstract class abstractclass<t extends someinterface> { public void dofoo() { // stuff } }
Comments
Post a Comment