001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.collections4.functors; 018 019import java.io.Serializable; 020 021import org.apache.commons.collections4.Closure; 022import org.apache.commons.collections4.Transformer; 023 024/** 025 * Transformer implementation that calls a Closure using the input object 026 * and then returns the input. 027 * 028 * @since 3.0 029 * @version $Id: ClosureTransformer.html 972421 2015-11-14 20:00:04Z tn $ 030 */ 031public class ClosureTransformer<T> implements Transformer<T, T>, Serializable { 032 033 /** Serial version UID */ 034 private static final long serialVersionUID = 478466901448617286L; 035 036 /** The closure to wrap */ 037 private final Closure<? super T> iClosure; 038 039 /** 040 * Factory method that performs validation. 041 * 042 * @param <T> the type of the object to transform 043 * @param closure the closure to call, not null 044 * @return the <code>closure</code> transformer 045 * @throws IllegalArgumentException if the closure is null 046 */ 047 public static <T> Transformer<T, T> closureTransformer(final Closure<? super T> closure) { 048 if (closure == null) { 049 throw new IllegalArgumentException("Closure must not be null"); 050 } 051 return new ClosureTransformer<T>(closure); 052 } 053 054 /** 055 * Constructor that performs no validation. 056 * Use <code>closureTransformer</code> if you want that. 057 * 058 * @param closure the closure to call, not null 059 */ 060 public ClosureTransformer(final Closure<? super T> closure) { 061 super(); 062 iClosure = closure; 063 } 064 065 /** 066 * Transforms the input to result by executing a closure. 067 * 068 * @param input the input object to transform 069 * @return the transformed result 070 */ 071 public T transform(final T input) { 072 iClosure.execute(input); 073 return input; 074 } 075 076 /** 077 * Gets the closure. 078 * 079 * @return the closure 080 * @since 3.1 081 */ 082 public Closure<? super T> getClosure() { 083 return iClosure; 084 } 085 086}