001/*
002 * Copyright 2002-2012 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.scheduling.support;
018
019import java.lang.reflect.InvocationTargetException;
020import java.lang.reflect.Method;
021import java.lang.reflect.UndeclaredThrowableException;
022
023import org.springframework.util.ReflectionUtils;
024
025/**
026 * Variant of {@link MethodInvokingRunnable} meant to be used for processing
027 * of no-arg scheduled methods. Propagates user exceptions to the caller,
028 * assuming that an error strategy for Runnables is in place.
029 *
030 * @author Juergen Hoeller
031 * @since 3.0.6
032 * @see org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor
033 */
034public class ScheduledMethodRunnable implements Runnable {
035
036        private final Object target;
037
038        private final Method method;
039
040
041        public ScheduledMethodRunnable(Object target, Method method) {
042                this.target = target;
043                this.method = method;
044        }
045
046        public ScheduledMethodRunnable(Object target, String methodName) throws NoSuchMethodException {
047                this.target = target;
048                this.method = target.getClass().getMethod(methodName);
049        }
050
051
052        public Object getTarget() {
053                return this.target;
054        }
055
056        public Method getMethod() {
057                return this.method;
058        }
059
060
061        @Override
062        public void run() {
063                try {
064                        ReflectionUtils.makeAccessible(this.method);
065                        this.method.invoke(this.target);
066                }
067                catch (InvocationTargetException ex) {
068                        ReflectionUtils.rethrowRuntimeException(ex.getTargetException());
069                }
070                catch (IllegalAccessException ex) {
071                        throw new UndeclaredThrowableException(ex);
072                }
073        }
074
075}