I’m having something in my mind about generic casting for List, but honestly I don’t know if it’s possible to implement or not.
There is this code snippet in my application
public String getObjectACombo() {
List<ObjectA> listA = theDAO.getObjectA();
String combo = getCombo(listA, "rootA"); // --> This line
}
public String getObjectBCombo() {
List<ObjectB> listB = theDAO.getObjectB();
String combo = getCombo(listA, "rootA"); // --> This line
}
Firstly I was coding some routine for the lines mentioned as “–> This line”. But the two methods have the exact same algorithm to generate JSON string from List<?> which has been returned from the database. So I am thinking to replace them with a generic method, getCombo(List<T> list, String root). But the thing is I couldn’t mange to make it work.
public <T> String getCombo(List<T> list, String root) {
Iterator<T> listItr = list.iterator();
...
while ( listItr.hasNext() ) {
jsonObj.put(list.get(i).toJson()); // --> The Error line
}
}
The error happens of the “The Error line”. Both ObjectA.java and ObjectB.java have the toJson() method in them, but “The method toJson() is undefined for the type T” at the mentioned line.
I tried to cast it with (T) and Class.forName(), but neither of them had worked.
Is there any work around to this problem? Is it even possible?
Use an interface that defines the
toJson()method, e.g.Jsonable🙂 – and then restrictT:This way the compiler knows that each
Tmust inherit fromJsonableand thus has thetoJson()method.Edit: here’s an example of what I mean, using the already existing
Comparable<T>interface: