How to create a JAR file with all classes and byte

2019-09-16 00:33发布

问题:

I am new to java and currently doing a java project. This is the instruction on how to submit the project. Could anyone tell me how to do this in either intelliJ or eclipse?

Please submit a Java Archive (jar file containing all java classes you have written). Your jar file should contain: a) Contain source code for all classes b) Contain executable (byte code) for all classes

回答1:

This question has been already answered here multiple times.

Since you also need to include the sources, you will have to change the resource patterns so that .java files are also copied to the compiler output and are therefore included in the .jar file.

By default .java files are excluded from copying, so you need to remove !?*.java; pattern that excludes them:

!?*.java;!?*.form;!?*.class;!?*.groovy;!?*.scala;!?*.flex;!?*.kt;!?*.clj;!?*.aj

becomes

!?*.form;!?*.class;!?*.groovy;!?*.scala;!?*.flex;!?*.kt;!?*.clj;!?*.aj

Don't forget to change it back for your real world applications.

If you need a sample project for IntelliJ IDEA, you can download it from my another answer. It shows a more complicated example where additional dependent jars are included into the project using different ways (single jar and multiple jars).



回答2:

If you you are using eclipse you can follow one of the below ways as per your requirements.

To Export the project you are working as jar:

1) Right Click on the project you are working > Select Export from context menu.

2) Select Java > JAR File

3) Select the project to export as JAR. Enter the name for the generating jar file and then click on finish.

If you are using Maven do following configurations to the pom.xml

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>2.4.1</version>
    <configuration>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
        <archive>
            <manifest>
                <mainClass>com.xxxxx.xxxxx</mainClass>
            </manifest>
        </archive>
        <outputDirectory>C:\tmp</outputDirectory>
    </configuration>
    <executions>
        <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
</plugin>

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-source-plugin</artifactId>
    <version>3.0.1</version>    
    <configuration>
        <outputDirectory>C:\tmp</outputDirectory>
    </configuration>    
    <executions>
        <execution>
            <id>attach-sources</id>
            <goals>
                <goal>jar</goal>
            </goals>
        </execution>
    </executions>
</plugin>