001package net.gdface.thrift;
002
003import com.google.common.base.Function;
004import com.google.common.base.Throwables;
005
006import static com.google.common.base.Preconditions.*;
007
008import java.lang.reflect.Constructor;
009
010/**
011 * 提供装饰对象{@link ThriftDecorator}和被装饰对象之间的类型转换
012 * @author guyadong
013 *
014 * @param <L>
015 * @param <R>
016 */
017public class ThriftDecoratorTransformer<L ,R extends ThriftDecorator<L> > {
018
019        private final Constructor<R> constructor;
020
021        public ThriftDecoratorTransformer(Class<L> left,Class<R> right) {
022                checkArgument(null != left && null != right,"left or right is null");
023                try {
024                        constructor = right.getConstructor(left);                       
025                } catch (Exception e) {
026                        Throwables.throwIfUnchecked(e);
027                        throw new RuntimeException(e);
028                }
029        }
030        /** 转换为thrift装饰对象{@link ThriftDecorator} */
031        public final Function<L,R> toDecoratorFun = new Function<L,R>(){
032                @Override
033                public R apply(L input) {
034                        try {
035                                return null == input ? null     : constructor.newInstance(input);
036                        } catch (Exception e) {
037                                Throwables.throwIfUnchecked(e);
038                                throw new RuntimeException(e);
039                        }
040                }};
041        /** 转为被装饰对象 */
042        public final  Function<R,L> toDelegateFun = new Function<R,L>(){
043                @Override
044                public L apply(R input) {
045                        return null == input ? null : input.delegate();
046                }};
047}