In addition to the language level and framework level learning, there are some things that have always existed in the JAVA language, but they have not been paid enough attention to because they are taken for granted. For example, what is a JAR?
When you think of jars, the first thing that comes to mind is a dependency, such as fastjson.jar, which can be referenced as a dependency in a project but cannot be executed through a Java-JAR, which is a non-executable JAR. Another type, such as the JAR (or WAR) generated after our project is packaged, is the Java-JAR, which we call an executable JAR.
JAR functions can be divided into the following categories:
- For publishing and using class libraries
- As building blocks for applications and extensions
- Unit of deployment for a component, applet, or plug-in
- Used to package secondary resources associated with components
The basic concept
A JAR file is an archive file built in ZIP format with a.jar file extension. You can create or extract JAR files using the jar command delivered with the JDK. You can also use other zip compression tools, but the order of entries in the zip header is important because the MANIFEST file usually comes first. The file name inside the JAR file is Unicode text.
A JAR file (Java Archive) is a package file format that is usually used to aggregate a large number of Java class files, associated metadata, and resource files (text, images, etc.) into a file for distribution of Java platform applications or libraries.
That’s from Wikipedia
The JAR file format provides many advantages and features, many of which traditional compression formats such as ZIP or TAR do not provide. They include:
- Security: JAR file contents can be digitally signed. That way, a tool that recognizes signatures can selectively grant you software security privileges that no other file can, and it can detect if the code has been tampered with.
- Reduce download time: If an applet is bundled into a JAR file, the browser can download the applet’s class files and associated resources in an HTTP transaction, rather than opening a new connection for each file.
- Compression: The JAR format allows you to compress files for efficient storage.
- Transmission platform extension. The Java Extensions Framework provides a way to add functionality to the Java core platform, packaged in JAR files (Java 3D and JavaMail are examples of Extensions developed by Sun).
- Package sealing: Packages stored in JAR files can optionally be sealed to enhance version consistency and security. Sealing a package means that all classes in the package must be found in the same JAR file.
- Package versioning: A JAR file can contain data about the files it contains, such as vendor and version information.
- Portability: The mechanism for handling JAR files is a standard part of the Java platform’s core APIS.
JAR file format
Here are two examples of decompressed JARS
Ordinary JAR decompressed file directory
Take Fastjson as an example:
. ├ ─ ─ meta-inf │ ├ ─ ─ LICENSE. TXT │ ├ ─ ─ the MANIFEST. The MF │ ├ ─ ─ NOTICE. TXT │ ├ ─ ─ maven │ │ └ ─ ─ com. Alibaba │ │ └ ─ ─ fastjson │ │ ├ ─ ─ pom. The properties │ │ └ ─ ─ pom. The XML │ └ ─ ─ services │ ├ ─ ─ javax.mail. Ws. Rs. Ext MessageBodyReader │ ├ ─ ─ Javax.mail. Ws. Rs. Ext MessageBodyWriter │ ├ ─ ─ javax.mail. Ws. Rs. Ext will │ └ ─ ─ Org. Anyone. Jersey. Internal. Spi. AutoDiscoverable └ ─ ─ com └ ─ ─ alibaba └ ─ ─ fastjson ├ ─ ─ JSON. The class ├ ─ ─ JSONArray. Class Anti-flag ── Anti-Flag. Class Anti-Flag ─ Anti-Flag ─ Anti-Flag jsonObject.class.... omitCopy the code
Executable JARS (using SpringBoot’s FAT Jar as an example)
This JAR is packaged with the simplest demo downloaded from start.spring. IO
├ ─ ─ the BOOT - INF │ ├ ─ ─ classes │ │ ├ ─ ─ application. The properties │ │ └ ─ ─ com │ │ └ ─ ─ exampleThe application's. Class file directory│ ├ ─ ├ ─ garbage ─ ├ ─ garbageMaven-dependent JAR files are stored here│ ├ ─ ─ javax.mail. The annotation - API - 1.3.2. Jar │ ├ ─ ─ jul - to - slf4j - 1.7.26. Jar │ ├ ─ ─log4 j - API - 2.11.2 jar │ ├ ─ ─log4 j - to - slf4j - 2.11.2. Jar │ ├ ─ ─ logback - classic - 1.2.3. Jar │ ├ ─ ─ logback - core - 1.2.3. Jar │ ├ ─ ─ slf4j - API - 1.7.26. Jar │ ├ ─ ─ Snakeyaml - 1.23. Jar │ ├ ─ ─ spring aop -- 5.1.8. The jar │ ├ ─ ─ spring - beans - 5.1.8. The jar │ ├ ─ ─ │ ├─ Spring-boot-Auto.2.1.6.release.jar │ ├─ Spring-boot-Auto.2.1.6.release.jar │ ├─ Spring-boot-Auto.2.1.6.release ├─ Spring-boot-starter 2.1.6.release.jar │ ├─ Spring-boot-starter 2.1.6.6.release. Jar │ ├─ Spring-boot-starter 2.1.6.6.release Spring - the context - 5.1.8. RELEASE. Jar │ ├ ─ ─ spring - core - 5.1.8. The jar │ ├ ─ ─ spring - expression - 5.1.8. The jar │ └ ─ ─ Spring - the JCL - 5.1.8. RELEASE. Jar ├ ─ ─ meta-inf │ ├ ─ ─ the MANIFEST. The MF │ └ ─ ─ maven │ └ ─ ─ com. Example │ └ ─ ─ demo │ ├ ─ ─ Pom. The properties │ └ ─ ─ pom. XML └ ─ ─ org └ ─ ─ springframework └ ─ ─ the boot └ ─ ─ loaderSpring Boot Loader class file├ ─ ─ ExecutableArchiveLauncher. Class ├ ─ ─ JarLauncher. Class ├ ─ ─ LaunchedURLClassLoader$UseFastConnectionExceptionsEnumeration.class ├ ─ ─ LaunchedURLClassLoader. Class ├ ─ ─ the Launcher. The class ├ ─ ─ MainMethodRunner. Class ├ ─ ─ PropertiesLauncherThe $1.class ├ ─ ─ PropertiesLauncher$ArchiveEntryFilter.class ├ ─ ─ PropertiesLauncher$PrefixMatchingArchiveFilter.Class ├── Traditional school. Class ├─ Traditional school$Entry.class │ ├ ─ ─... ├─ Data │ ├─ Finger Exercises. Class │ ├─ Finger Exercises... ├── ── ── ── ── ── ── ── ──... └ ─ ─ util └ ─ ─ SystemPropertyUtils. ClassCopy the code
META-INF
Most JAR files contain a meta-INF directory, which is used to store configuration data such as security and version information for packages and extensions. The Java 2 platform (standard [J2SE]) identifies and interprets the following files and directories in the META-INF directory to configure applications, extensions, and classloaders:
- Manifest.mf: This MANIFEST file defines data related to extensions and packages.
- Files packaged via MAVEN plugins such as:
- maven
- Services: Stores all service provider configuration files
- Others that you don’t usually see:
- Index.list: This file is generated by the new jar tool option -i and contains information about the location of packages defined in the application or extension. It is part of the JarIndex implementation and is used by the class loader to speed up the class loading process.
- .sf: This is the signature file of the JAR file
- .dsa: Signature program block file associated with the signature file, which stores the public signature used to sign the JAR file.
- License. TXT: indicates the certificate information
- Notice. TXT: indicates bulletin information
Executable JAR
The most direct difference between an executable JAR and a regular JAR is whether it can be executed through java-JAR.
An executable JAR file is a self-contained Java application stored in a specially configured JAR file that can be executed directly by the JVM without first extracting the file or setting the classpath. To run an application stored in a non-executable JAR, you must add it to your classpath and call the application’s main class by name. But with an executable JAR file, we can run an application without extracting it or knowing the main entry point. Executable jars help ease the publishing and execution of Java applications
An executable JAR must reference all other dependent jars it needs through the header of the Menifest file. If the -jar option is used, the environment variable CLASSPATH and all CLASSPATH specified on the command line are ignored by the JVM.
The MANIFEST. Manifest.mf
When the JAR command is used, the meta-INF directory will be created under the root directory. This directory will contain some descriptions of the JAR package information, including a manifest.mf file, which contains the version of the JAR package, the creator, and the class search path.
-
Manifest.mf file in the FASTJSON JAR
The Manifest - Version: 1.0Define the version of the manifest file Archiver-Version: Plexus Archiver # http://codehaus-plexus.github.io/plexus-archiver/ Built-By: wenshao # builderCreated - By: Apache Maven 3.5.0# # Declares the producer of this file. Typically this property is generated by the JAR command line toolThe Build - Jdk: 1.8.0 comes with _162# Build based JDK version Copy the code
-
SpringBoot Demo manifest.mf file
The Manifest - Version: 1.0 Implementation - the Title: demo# defines the title of the extension implementationImplementation - Version: 0.0.1 - the SNAPSHOTDefine the version of the extension implementation Start-Class: com.example.demo.DemoApplication # start class Spring-Boot-Classes: BOOT-INF/classes/ The compiled class file directory Spring-Boot-Lib: BOOT-INF/lib/ The current project depends on the jar package directoryBuild Jdk - Spec: 1.8# Specifies the JDK versionSpring - the Boot - Version: 2.1.6. RELEASE# SpringBoot versionCreated By: - Maven Archiver 3.4.0 Main - Class: org. Springframework.. The boot loader. JarLauncher# Main function Copy the code
In the Java platform, the MANIFEST file is a special file contained in a JAR archive that is used to define extensions or file packaging related data.
The MANIFEST file acts as a metadata file that contains k-V pairs of data in different parts.
If a JAR file is treated as an executable, the MANIFEST file in it needs to indicate the program’s main class file, as shown in the JAR for the SpringBoot demo in the case above
The MANIFEST function
You can get a basic idea of what it does from the information in the MANIFEST file
- Basic information about the JAR package
- Main-class specifies the entry to the program so that it can be run directly with java-jar xxx.jar
- Class-path specifies the jar dependencies. The Class loader searches for classes based on this Path
To get the MANIFEST. MF
The MANIFEst.mf file in a JAR package is a tool provided in the JDK, which can be obtained from the java.util.jar class library.
JarFile jar = new JarFile(new File("/ Users/glmapper/Documents/test/demo/target/demo - 0.0.1 - the SNAPSHOT. Jar"));
Manifest manifest = jar.getManifest();
Attributes mainAttributes = manifest.getMainAttributes();
for(Map.Entry<Object, Object> attrEntry : mainAttributes.entrySet()){
System.out.println("main\t"+attrEntry.getKey()+":"+attrEntry.getValue());
}
Map<String, Attributes> entries = manifest.getEntries();
for(Map.Entry<String, Attributes> entry : entries.entrySet()) {
Attributes values = entry.getValue();
for (Map.Entry<Object, Object> attrEntry : values.entrySet()) {
System.out.println(attrEntry.getKey() + ":"+ attrEntry.getValue()); }}Copy the code
The execution result is as follows:
Main implementation-title: Demo main implementation-version :0.0.1-SNAPSHOT main Start-Class:com.example.demo.DemoApplication main Spring-Boot-Classes:BOOT-INF/classes/ main Spring-boot-lib: boot-INF/Lib/main build-jdk-spec :1.8 main spring-boot-version :2.1.6.RELEASE main Created-By:Maven Archiver 3.4.0 main Manifest - Version: 1.0 the main main - Class: org. Springframework.. The boot loader. JarLauncherCopy the code
Jar files and Manifest are defined in Java
The following is the definition of JarFile. As you can see from the code, the Jar we introduced earlier builds an archive in ZIP format because it is a subclass of ZipFile.
public class JarFile extends ZipFile {
private SoftReference<Manifest> manRef;
private JarEntry manEntry;
private JarVerifier jv;
private boolean jvInitialized;
private boolean verify;
/ / indicate whether there is a Class - Path attribute (is valid only when the hasCheckedSpecialAttributes is true)
private boolean hasClassPathAttribute;
True if the manifest checks for special attributes
private volatile boolean hasCheckedSpecialAttributes;
// Set JavaUtilJarAccess in SharedSecrets
static {
SharedSecrets.setJavaUtilJarAccess(new JavaUtilJarAccessImpl());
}
/**
* The JAR manifest file name.(JAR清单文件名)
*/
public static final String MANIFEST_NAME = "META-INF/MANIFEST.MF";
// omit others
}
Copy the code
Below is the definition of the Manifest class, which describes the Manifest file of the JAR. It is also well observed from its properties that it stores k-V key-value pair data.
public class Manifest implements Cloneable {
// manifest main attributes
private Attributes attr = new Attributes();
// manifest entries
private Map<String, Attributes> entries = new HashMap<>();
// omit others
}
Copy the code
summary
Far more than a compressed format, the JAR format has many features that can improve efficiency, security, and organization of Java applications. Because these capabilities are already built into the core platform, including compilers and classloaders, developers can take advantage of the JAR file format’s capabilities to simplify and improve the development and deployment process.
Attached: Common JAR tool usage
function | The command |
---|---|
Create a JAR file from a separate file | jar cf jar-file input-file… |
Create a JAR file from a directory | jar cf jar-file dir-name |
Create an uncompressed JAR file | jar cf0 jar-file dir-name |
Update a JAR file | jar uf jar-file input-file… |
View the contents of a JAR file | jar tf jar-file |
Extracts the contents of a JAR file | jar xf jar-file |
Extract a specific file from a JAR file | jar xf jar-file archived-file… |
Run an application packaged as an executable JAR file | java -jar app.jar |
reference
- JAR files are disclosed
- JAR
- JAR File Specification