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

you can't.

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

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -