简体   繁体   中英

How to cast List<T> to be able to call specific method on respective Object?

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, eg Jsonable :) - and then restrict T :

public <T extends Jsonable> String getCombo(List<T> list, String root) { 
 ...
}

This way the compiler knows that each T must inherit from Jsonable and thus has the toJson() method.

Edit: here's an example of what I mean, using the already existing Comparable<T> interface:

public <T extends Comparable<T>> boolean compare(List<T> list, T other) {
  for( T object : list ) {
    if( object.compareTo( other ) == 0 ) {
      return true;
    }
  }    
  return false;
}

compare( new ArrayList<String>(), "foo"); //compiles, since String implements Comparable<String>
compare( new ArrayList<Object>(), null); //doesn't compile, since Object doesn't implement Comparable<Object>

Try to use a for each:

public <T> String getCombo( List<T> list, String root )
{
    for (T x : list)
    {
        //do stuff here
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM