Java examples for Reflection:Jar
execute Jar file
/*//w w w . j a va 2 s .c om * Copyright @ 2006-2010 by The Jxva Framework Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //package com.java2s; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.zip.ZipFile; public class Main { public static void exec(File jarFile, ArrayList<?> argsList, ClassLoader classLoader) throws IOException, ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { String[] args = (String[]) argsList.toArray(new String[argsList .size()]); exec(jarFile, args, classLoader); } public static void exec(File jarFile, String[] args, ClassLoader classLoader) throws IOException, ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { String mainClassName = getMainClassName(jarFile); if (mainClassName == null) { throw new ClassNotFoundException( "Unable to extract name of Main-Class of " + jarFile.getAbsolutePath()); } Class<?> mainClass = classLoader.loadClass(mainClassName); Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class }); mainMethod.invoke(null, new Object[] { args }); } /** * Extracts the name of the main class from the given jar file. * * @param jarFile the jar file * @return the name of the main class from the given jar file, null when the jar does not have a manifest. * @throws IOException when the jar file could not be read */ public static String getMainClassName(File jarFile) throws IOException { if (!jarFile.exists()) { throw new IllegalArgumentException("File [" + jarFile.getAbsolutePath() + "] does not exist."); } JarFile input = new JarFile(jarFile, false, ZipFile.OPEN_READ); Manifest manifest = input.getManifest(); if (manifest == null) { return null; } Attributes attributes = manifest.getMainAttributes(); if (attributes != null) { return attributes.getValue("Main-Class"); } return null; } }