简体   繁体   中英

Apache Poi best way

Hi last time I was wondering about good way to save object by Apche Poi.

Way 1

List<Something> list = ....;
cell.setValue(obj.getName) etc

Way 2 Convert List to Object[]

for(int i=0; i<objectsToSave.size;i++){
 for(int y=0; y<object.size;y++){
  if(obj instance of Integer)
   cell.setValue((Integer) obj[i]
  if(obj instance of RichTextString)
   cell.setValue((RichTextString) obj[i]
 }
}

In 1 way I don't have if's but if we want to save another object we have to create new "converter".

In 2 way is "universal" but I can have many if's. (I think it's bad practise)

Do you have any idea/ good way for it?

There really isn't a great way of doing this. One thing you could try to avoid the repeated type-checking is to create a map of setters, like this:


private static Map<Class<?>,BiConsumer<Cell,Object>> typeMap = new HashMap<Class<?>, BiConsumer<Cell,Object>>();

static {
   typeMap.put(Integer.class, obj -> cell.setValue((Integer)obj);
   typeMap.put(String.class, obj -> cell.setValue((RichTextString)obj);
//....and so on
}

public void setCell(Cell cell, Object obj) {
   typeMap.get(obj.getClass()).apply(cell, obj);
}

Then your code would become:

for(int i=0; i<objectsToSave.size;i++){
 for(int y=0; y<object.size;y++){
  setCell(cell, object);
 }
}

This has the advantage of avoiding the repeated RTTI of instanceof but it can be dangerous, in particular you have to be careful to exhaustively check for every class, or throw an exception.

It's still not great, though; all you're doing is, essentially, moving the conditional.

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