[英]Apache Poi best way
Hi last time I was wondering about good way to save object by Apche Poi.嗨,上次我想知道 Apche Poi 保存对象的好方法。
Way 1方式一
List<Something> list = ....;
cell.setValue(obj.getName) etc
Way 2 Convert List to Object[]方式 2 将列表转换为对象[]
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".在一种方式中,我没有 if,但是如果我们想保存另一个对象,我们必须创建新的“转换器”。
In 2 way is "universal" but I can have many if's. In 2 way是“通用的”,但我可以有很多if。 (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:
您可以尝试避免重复类型检查的一件事是创建一个 setter 映射,如下所示:
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.这具有避免
instanceof
重复 RTTI 的优点,但它可能很危险,特别是您必须小心地彻底检查每个类,否则会引发异常。
It's still not great, though;不过,它仍然不是很好。 all you're doing is, essentially, moving the conditional.
您所做的基本上就是移动条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.