JarURLConnection

java.net.JarURLConnection Example

In this example we shall show you how to make use of JarURLConnection class, This class establishes a connection to a jar URL using the JAR protocol. A JarURLConnection instance can refer to either a JAR archive file or to an entry of such a file. jar URLs are specified as follows: jar:{archive-url}!/{entry} where !/ is called a separator. This separator is important to determine if an archive or an entry of an archive is referred.

Examples:
Jar entry: jar:http://www.jcg.com/bar/baz.jar!/com/foo/Quux.class
Jar file: jar:http://www.jcg.com/bar/baz.jar!/
Jar directory: jar:http://www.jcg.com/bar/baz.jar!/com/foo/

Now, suppose that we have a main application. Also, we have a small application which is doing some logic for our main application. How we can run our small app which was packaged as a JAR file from inside our main app?

So, Let’s see the below example.

Example:

Bean.java:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
package com.jcg;
 
/**
 * @author ashraf
 *
 */
public class Bean {
     
    public static void main( String [] args) {
        sayHello();
    }
     
    public static void sayHello() {
        System.out.println("Hello from loaded JAR class !!!");
    }
 
}

JarURLConnectionTest.java:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.jcg;
 
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Map.Entry;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
 
/**
 * @author ashraf
 *
 */
public class JarURLConnectionTest {
     
    private final static String JAR_URL = "jar:file:/C:/Users/ashraf_sarhan/simple-bean-1.0.jar!/";
    private final static String JAR_FILE_PATH = "file:/C:/Users/ashraf_sarhan/simple-bean-1.0.jar";
    private static URLClassLoader urlClassLoader;
 
    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
 
        try {
 
            // Create a URL that refers to a jar file in the file system
            URL FileSysUrl = new URL(JAR_URL);
 
            // Create a jar URL connection object
            JarURLConnection jarURLConnection = (JarURLConnection)FileSysUrl.openConnection();
             
            // Get the jar file
            JarFile jarFile = jarURLConnection.getJarFile();
             
            // Get jar file name
            System.out.println("Jar Name: " + jarFile.getName());
             
            // When no entry is specified on the URL, the entry name is null
            System.out.println("\nJar Entry: " + jarURLConnection.getJarEntry());
             
            // Get the manifest of the jar
            Manifest manifest = jarFile.getManifest();
 
            // Print the manifest attributes
            System.out.println("\nManifest file attributes: ");
            for (Entry entry : manifest.getMainAttributes().entrySet()) {
                System.out.println(entry.getKey() +": "+ entry.getValue());
            }
            System.out.println("\nExternal JAR Execution output: ");
 
            // Get the jar URL which contains target class
            URL[] classLoaderUrls = new URL[]{new URL(JAR_FILE_PATH)};
 
            // Create a classloader and load the entry point class
            urlClassLoader = new URLClassLoader(classLoaderUrls);
 
            // Get the main class name (the entry point class)
            String mainClassName = manifest.getMainAttributes().getValue(Attributes.Name.MAIN_CLASS); 
 
            // Load the target class
            Class beanClass = urlClassLoader.loadClass(mainClassName);
 
            // Get the main method from the loaded class and invoke it
            Method method = beanClass.getMethod("main", String[].class);
 
            // init params accordingly
            String[] params = null;
 
            // static method doesn't have an instance
            method.invoke(null, (Object) params);
 
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
    }
 
}

Output:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
Jar Name: C:\Users\ashraf_sarhan\simple-bean-1.0.jar
 
Jar Entry: null
 
Manifest file attributes:
Build-Jdk: 1.7.0_40
Built-By: ashraf_sarhan
Manifest-Version: 1.0
Created-By: Apache Maven
Main-Class: com.jcg.Bean
Archiver-Version: Plexus Archiver
 
External JAR Execution output:
Hello from loaded JAR class !!!

Explanation:

In the above example, It’s possible you don’t know the main class of the JAR file which you need to run it so we loaded our simple-bean-1.0.jar file which print a message to console using JarURLConnection and reading its Manifest to find the entry point class (i.e., main class name – com.jcg.Bean), then we create a classloader and load the entry point class. Finally, we are using reflection to get its public static void main(String[]) method and invoke it.

Tip

When constructing a JAR url via new URL(context, spec), the following rules apply:

  • if there is no context URL and the specification passed to the URL constructor doesn’t contain a separator, the URL is considered to refer to a JarFile.
  • if there is a context URL, the context URL is assumed to refer to a JAR file or a Jar directory.
  • if the specification begins with a ‘/’, the Jar directory is ignored, and the spec is considered to be at the root of the Jar file.

Examples:

context: jar:http://www.jcg.com/bar/jar.jar!/, spec: baz/entry.txt
url: jar:http://www.jcg.com/bar/jar.jar!/baz/entry.txt

context: jar:http://www.jcg.com/bar/jar.jar!/baz, spec: entry.txt
url: jar:http://www.jcg.com/bar/jar.jar!/baz/entry.txt

context: jar:http://www.jcg.com/bar/jar.jar!/baz, spec: /entry.txt
url: jar:http://www.jcg.com/bar/jar.jar!/entry.txt

Download the Source Code of this example:

This was an example of how to use JarURLConnection class.

Download
You can download the full source code of this example here: java.net.JarURLConnection Example Code

Ashraf Sarhan

Ashraf Sarhan is a passionate software engineer, an open source enthusiast, has a Bsc. degree in Computer and Information Systems from Alexandria University. He is experienced in building large, scalable and distributed enterprise applications/service in multiple domains. He also has a keen interest in JavaEE, SOA, Agile and Big Data technologies.
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button