001package org.jadira.reflection.access.portable;
002
003import java.lang.reflect.InvocationTargetException;
004import java.lang.reflect.Method;
005
006import org.jadira.reflection.access.api.MethodAccess;
007
008public class PortableMethodAccess<C> implements MethodAccess<C> {
009
010        private Method method;
011        private Class<C> declaringClass;
012        private Class<?> returnType;
013
014        @SuppressWarnings("unchecked")
015        private PortableMethodAccess(Method m) {
016                this.method = m;
017                if (!method.isAccessible()) {
018                        method.setAccessible(true);
019                }
020                this.declaringClass = (Class<C>) m.getDeclaringClass();
021                this.returnType = (Class<?>) m.getReturnType();
022        }
023        
024        public static <C> PortableMethodAccess<C> get(Method m) {
025                
026                return new PortableMethodAccess<C>(m);
027        }
028        
029        @Override
030        public Class<C> declaringClass() {
031                return declaringClass;
032        }
033
034        @Override
035        public Class<?> returnClass() {
036                return returnType;
037        }
038
039        @Override
040        public Method method() {
041                return method;
042        }
043        
044        @Override
045        public Object invoke(Object target, Object... args) throws IllegalArgumentException {
046                
047                try {
048                        return method.invoke(target, args);
049                } catch (IllegalAccessException e) {
050                        throw new IllegalArgumentException("Could not invoke: " + e.getMessage(), e);
051                } catch (InvocationTargetException e) {
052                        throw new IllegalArgumentException("Could not invoke: " + e.getMessage(), e);
053                }
054        }
055}