001/*
002 * Copyright 2006-2007 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.batch.item.file.transform;
018
019import java.util.ArrayList;
020import java.util.Arrays;
021import java.util.List;
022
023import org.springframework.beans.BeanWrapper;
024import org.springframework.beans.BeanWrapperImpl;
025import org.springframework.beans.factory.InitializingBean;
026import org.springframework.util.Assert;
027
028/**
029 * This is a field extractor for a java bean. Given an array of property names,
030 * it will reflectively call getters on the item and return an array of all the
031 * values.
032 * 
033 * @author Dan Garrette
034 * @since 2.0
035 */
036public class BeanWrapperFieldExtractor<T> implements FieldExtractor<T>, InitializingBean {
037
038        private String[] names;
039
040        /**
041         * @param names field names to be extracted by the {@link #extract(Object)} method.
042         */
043        public void setNames(String[] names) {
044                Assert.notNull(names, "Names must be non-null");
045                this.names = Arrays.asList(names).toArray(new String[names.length]);
046        }
047
048        /**
049         * @see org.springframework.batch.item.file.transform.FieldExtractor#extract(java.lang.Object)
050         */
051    @Override
052        public Object[] extract(T item) {
053                List<Object> values = new ArrayList<Object>();
054
055                BeanWrapper bw = new BeanWrapperImpl(item);
056                for (String propertyName : this.names) {
057                        values.add(bw.getPropertyValue(propertyName));
058                }
059                return values.toArray();
060        }
061
062    @Override
063        public void afterPropertiesSet() {
064                Assert.notNull(names, "The 'names' property must be set.");
065        }
066}