    001package com.hammurapi.extract;
    002
    003import java.lang.reflect.InvocationTargetException;
    004import java.lang.reflect.Method;
    005import java.lang.reflect.Modifier;
    006import java.util.Collections;
    007import java.util.Map;
    008import java.util.Set;
    009import java.util.TreeSet;
    010import java.util.concurrent.TimeUnit;
    011
    012public class MethodExtractor<T, V, C> extends ExtractorBase<T, V, C> implements     Extractor<T, V, C> {
    013
    014        private Method method;
    015        private Set<Integer> parameterIndices;
    016
    017        public MethodExtractor(double initialCost, TimeUnit costUnit, Method method) {
    018                super(initialCost, costUnit);
    019                this.method = method;
    020                Set<Integer> pi = new TreeSet<Integer>();
    021                for (int i=0, l=method.getParameterTypes().length; i<l; ++i) {
    022                        pi.add(i);
    023                }
    024                parameterIndices = Collections.unmodifiableSet(pi);
    025        }
    026
    027        @Override
    028        public Set<Integer> parameterIndices() {
    029                return parameterIndices;
    030        }
    031
    032        @Override
    033        public boolean isContextDependent() {
    034                return Modifier.isStatic(method.getModifiers());
    035        }
    036
    037        @SuppressWarnings("unchecked")
    038        @Override
    039        protected V extractInternal(
    040                        C context,
    041                        Map<C, Map<Extractor<T, ? super V, C>, ? super V>> cache,
    042                        T... obj) {
    043                try {
    044                        return (V) method.invoke(context, obj);
    045                } catch (IllegalAccessException e) {
    046                        throw new ExtractorException(e);
    047                } catch (InvocationTargetException e) {
    048                        throw new ExtractorException(e);
    049                }
    050        }
    051
    052
    053}