Java generic types and methods -


i want create function gets list parameter , creates jsonresult. know in advance every t object of mine have getid() function. method

private static <t> jsonobject createjsonaarrayresult(list<t> items, class<t> type){     jsonobject jsonresult = new jsonobject();     jsonarray jsonresultitem = new jsonarray();     (t item : items){         jsonobject jsonarrayitem = new jsonobject();         jsonresultitem.addproperty("id", item.getid());      }     return jsonresult; } 

the line calls item.getid() of course gives me error. how can bypass it. using type pass class type use casting. still error. there way use t , call methods specific object?

for example every of t implement interface of abstract class has function has getid().

e.g.:

public interface interfaceid {     string getid(); } 

then make sure each of types pass method use interface (or other interface/class may have) can declare generic extends:

 private static <t extends interfaceid> jsonobject createjsonaarrayresult(list<t> items){     ....     // class<t> parameter not needed in example , can removed. 

from on getid() function available.


Comments