Parse jar files in java, read and call

Source: Internet
Author: User

Processing Jar files in the application briefly introduces how to use java. util. the jar package provides APIs to operate jar files. The following describes some advanced applications related to Jar files through a relatively complex example. Read this article carefully and refer to the relevant java doc, which will be of great help for you to learn the java language.

The following applications load and execute a jar file from the http server. For example, the address of your Jar file is hello. jar. To implement this function, we should first establish a connection with this file, then obtain the value of Main-Class through MANIFEST information description, and finally load and run this class. Some important knowledge about java.net and reflection is required. This application consists of two classes: JarClassLoader and JarRunner.

JarClassLoader extends URLClassLoader, which has a URL variable of the url type.
 

 public JarClassLoader(URL url)   {     super(new URL[] { url });      this.url = url;  }

 

The two important methods are getMainClassName () and invokeClass (). The former aims to obtain the connection through URL and jar, it is important to read the Main-Class attribute of MANIFEST to obtain the application's entry point. After getting the entry point, we can load and run the main class through the reflection mechanism.

public String getMainClassName() throws IOException {    URL u = new URL("jar", "", url + "!/");    JarURLConnection uc = (JarURLConnection)u.openConnection();    Attributes attr = uc.getMainAttributes();    return attr != null                   ? attr.getValue(Attributes.Name.MAIN_CLASS)                   : null;}public void invokeClass(String name, String[] args) throws ClassNotFoundException,        NoSuchMethodException,        InvocationTargetException    { Class c = this.loadClass(name); Method m = c.getMethod("main", new Class[] { args.getClass() }); m.setAccessible(true); int mods = m.getModifiers(); if (m.getReturnType() != void.class || !Modifier.isStatic(mods) ||     !Modifier.isPublic(mods)) {     throw new NoSuchMethodException("main"); } try {     m.invoke(null, new Object[] { args }); } catch (IllegalAccessException e) {     // This should not happen, as we have disabled access checks } }    URL u = new URL("jar", "", url + "!/");    JarURLConnection uc = (JarURLConnection)u.openConnection();

 

These two pieces of code construct a JarURLConnection instance. Note! The/separator indicates that the url represents the entire jar file. In this way, the communication with the jar file is established. The following two sentences in the method are used to obtain the main class of the jar file. In the invokeClass method, we first obtain the main class including the program entry through the ClassLoader method, and then obtain the main method, after determining that the main Method is the Method we need, call the Method's invoke Method to execute this application.

The following is the source code.

import java.net.URL;import java.net.URLClassLoader;import java.net.JarURLConnection;import java.lang.reflect.Method;import java.lang.reflect.Modifier;import java.lang.reflect.InvocationTargetException;import java.util.jar.Attributes;import java.io.IOException;class JarClassLoader extends URLClassLoader {    private URL url;    public JarClassLoader(URL url) { super(new URL[] { url }); this.url = url;    }    public String getMainClassName() throws IOException { URL u = new URL("jar", "", url + "!/"); JarURLConnection uc = (JarURLConnection)u.openConnection(); Attributes attr = uc.getMainAttributes(); return attr != null ? attr.getValue(Attributes.Name.MAIN_CLASS) : null;    }    public void invokeClass(String name, String[] args) throws ClassNotFoundException,        NoSuchMethodException,        InvocationTargetException    { Class c = this.loadClass(name); Method m = c.getMethod("main", new Class[] { args.getClass() }); m.setAccessible(true); int mods = m.getModifiers(); if (m.getReturnType() != void.class || !Modifier.isStatic(mods) ||     !Modifier.isPublic(mods)) {     throw new NoSuchMethodException("main"); } try {     m.invoke(null, new Object[] { args }); } catch (IllegalAccessException e) {     // This should not happen, as we have disabled access checks }    }}
import java.io.IOException;import java.net.URL;import java.net.MalformedURLException;import java.lang.reflect.InvocationTargetException;/** * Runs a jar application from any url. Usage is 'java JarRunner url [args..]' * where url is the url of the jar file and args is optional arguments to * be passed to the application's main method. */public class JarRunner {    public static void main(String[] args) { if (args.length < 1) {     usage(); } URL url = null; try {     url = new URL(args[0]); } catch (MalformedURLException e) {     fatal("Invalid URL: " + args[0]); } // Create the class loader for the application jar file JarClassLoader cl = new JarClassLoader(url); // Get the application's main class name String name = null; try {     name = cl.getMainClassName(); } catch (IOException e) {     System.err.println("I/O error while loading JAR file:");     e.printStackTrace();     System.exit(1); } if (name == null) {     fatal("Specified jar file does not contain a 'Main-Class'" +    " manifest attribute"); } // Get arguments for the application String[] newArgs = new String[args.length - 1]; System.arraycopy(args, 1, newArgs, 0, newArgs.length); // Invoke application's main class try {     cl.invokeClass(name, newArgs); } catch (ClassNotFoundException e) {     fatal("Class not found: " + name); } catch (NoSuchMethodException e) {     fatal("Class does not define a 'main' method: " + name); } catch (InvocationTargetException e) {     e.getTargetException().printStackTrace();     System.exit(1); }    }    private static void fatal(String s) { System.err.println(s); System.exit(1);    }    private static void usage() { fatal("Usage: java JarRunner url [args..]");    }}

 

Compile a simple HelloWorld program and create a jar package. Note that the MANIFEST file in your jar package must include Main-Class: HelloWorld. Otherwise, the program entry cannot be found. Put it on a web server, such as http: // localhost/hello. jar. Compile the source program and execute
Java JarRunner http: // localhost/hello. jar (which can contain parameters). On the console, we can see the hello world output!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.