1 /*
2 * Copyright 2006-2007 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.springframework.batch.item.file.transform;
18
19 import java.util.ArrayList;
20 import java.util.Arrays;
21 import java.util.List;
22
23 import org.springframework.beans.BeanWrapper;
24 import org.springframework.beans.BeanWrapperImpl;
25 import org.springframework.beans.factory.InitializingBean;
26 import org.springframework.util.Assert;
27
28 /**
29 * This is a field extractor for a java bean. Given an array of property names,
30 * it will reflectively call getters on the item and return an array of all the
31 * values.
32 *
33 * @author Dan Garrette
34 * @since 2.0
35 */
36 public class BeanWrapperFieldExtractor<T> implements FieldExtractor<T>, InitializingBean {
37
38 private String[] names;
39
40 /**
41 * @param names field names to be extracted by the {@link #extract(Object)} method.
42 */
43 public void setNames(String[] names) {
44 Assert.notNull(names, "Names must be non-null");
45 this.names = Arrays.asList(names).toArray(new String[names.length]);
46 }
47
48 /**
49 * @see org.springframework.batch.item.file.transform.FieldExtractor#extract(java.lang.Object)
50 */
51 @Override
52 public Object[] extract(T item) {
53 List<Object> values = new ArrayList<Object>();
54
55 BeanWrapper bw = new BeanWrapperImpl(item);
56 for (String propertyName : this.names) {
57 values.add(bw.getPropertyValue(propertyName));
58 }
59 return values.toArray();
60 }
61
62 @Override
63 public void afterPropertiesSet() {
64 Assert.notNull(names, "The 'names' property must be set.");
65 }
66 }