001/*
002 * Copyright 2012-2018 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 *      http://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.boot.loader;
018
019import java.lang.reflect.Method;
020
021/**
022 * Utility class that is used by {@link Launcher}s to call a main method. The class
023 * containing the main method is loaded using the thread context class loader.
024 *
025 * @author Phillip Webb
026 * @author Andy Wilkinson
027 */
028public class MainMethodRunner {
029
030        private final String mainClassName;
031
032        private final String[] args;
033
034        /**
035         * Create a new {@link MainMethodRunner} instance.
036         * @param mainClass the main class
037         * @param args incoming arguments
038         */
039        public MainMethodRunner(String mainClass, String[] args) {
040                this.mainClassName = mainClass;
041                this.args = (args != null) ? args.clone() : null;
042        }
043
044        public void run() throws Exception {
045                Class<?> mainClass = Thread.currentThread().getContextClassLoader()
046                                .loadClass(this.mainClassName);
047                Method mainMethod = mainClass.getDeclaredMethod("main", String[].class);
048                mainMethod.invoke(null, new Object[] { this.args });
049        }
050
051}