1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.collections4.functors;
18
19 import java.io.Serializable;
20
21 import org.apache.commons.collections4.Closure;
22 import org.apache.commons.collections4.Transformer;
23
24 /**
25 * Closure implementation that calls a Transformer using the input object
26 * and ignore the result.
27 *
28 * @param <T> the type of the input to the operation.
29 * @since 3.0
30 */
31 public class TransformerClosure<T> implements Closure<T>, Serializable {
32
33 /** Serial version UID */
34 private static final long serialVersionUID = -5194992589193388969L;
35
36 /**
37 * Factory method that performs validation.
38 * <p>
39 * A null transformer will return the {@code NOPClosure}.
40 *
41 * @param <E> the type that the closure acts on
42 * @param transformer the transformer to call, null means nop
43 * @return the {@code transformer} closure
44 */
45 public static <E> Closure<E> transformerClosure(final Transformer<? super E, ?> transformer) {
46 if (transformer == null) {
47 return NOPClosure.<E>nopClosure();
48 }
49 return new TransformerClosure<>(transformer);
50 }
51
52 /** The transformer to wrap */
53 private final Transformer<? super T, ?> iTransformer;
54
55 /**
56 * Constructor that performs no validation.
57 * Use {@code transformerClosure} if you want that.
58 *
59 * @param transformer the transformer to call, not null
60 */
61 public TransformerClosure(final Transformer<? super T, ?> transformer) {
62 iTransformer = transformer;
63 }
64
65 /**
66 * Executes the closure by calling the decorated transformer.
67 *
68 * @param input the input object
69 */
70 @Override
71 public void execute(final T input) {
72 iTransformer.apply(input);
73 }
74
75 /**
76 * Gets the transformer.
77 *
78 * @return the transformer
79 * @since 3.1
80 */
81 public Transformer<? super T, ?> getTransformer() {
82 return iTransformer;
83 }
84
85 }