1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.supercsv.io;
17
18 import java.io.IOException;
19 import java.io.Writer;
20 import java.lang.reflect.Method;
21 import java.util.ArrayList;
22 import java.util.List;
23
24 import org.supercsv.cellprocessor.ift.CellProcessor;
25 import org.supercsv.exception.SuperCsvReflectionException;
26 import org.supercsv.prefs.CsvPreference;
27 import org.supercsv.util.MethodCache;
28 import org.supercsv.util.Util;
29
30
31
32
33
34
35
36
37 public class CsvBeanWriter extends AbstractCsvWriter implements ICsvBeanWriter {
38
39
40 private final List<Object> beanValues = new ArrayList<Object>();
41
42
43 private final List<Object> processedColumns = new ArrayList<Object>();
44
45
46 private final MethodCache cache = new MethodCache();
47
48
49
50
51
52
53
54
55
56
57
58
59 public CsvBeanWriter(final Writer writer, final CsvPreference preference) {
60 super(writer, preference);
61 }
62
63
64
65
66
67
68
69
70
71
72
73
74
75 private void extractBeanValues(final Object source, final String[] nameMapping) {
76
77 if( source == null ) {
78 throw new NullPointerException("the bean to write should not be null");
79 } else if( nameMapping == null ) {
80 throw new NullPointerException(
81 "the nameMapping array can't be null as it's used to map from fields to columns");
82 }
83
84 beanValues.clear();
85
86 for( int i = 0; i < nameMapping.length; i++ ) {
87
88 final String fieldName = nameMapping[i];
89
90 if( fieldName == null ) {
91 beanValues.add(null);
92
93 } else {
94 Method getMethod = cache.getGetMethod(source, fieldName);
95 try {
96 beanValues.add(getMethod.invoke(source));
97 }
98 catch(final Exception e) {
99 throw new SuperCsvReflectionException(String.format("error extracting bean value for field %s",
100 fieldName), e);
101 }
102 }
103
104 }
105
106 }
107
108
109
110
111 public void write(final Object source, final String... nameMapping) throws IOException {
112
113
114 super.incrementRowAndLineNo();
115
116
117 extractBeanValues(source, nameMapping);
118
119
120 super.writeRow(beanValues);
121 }
122
123
124
125
126 public void write(final Object source, final String[] nameMapping, final CellProcessor[] processors)
127 throws IOException {
128
129
130 super.incrementRowAndLineNo();
131
132
133 extractBeanValues(source, nameMapping);
134
135
136 Util.executeCellProcessors(processedColumns, beanValues, processors, getLineNumber(), getRowNumber());
137
138
139 super.writeRow(processedColumns);
140 }
141 }