how to create a jar with compiled classes from a source jar in java
Asked Answered
A

2

6

I know how to create a jar from .java or .class files.

I have a sources.jar that contains .java files. I want to compile these classes and pack into a jar again.

for example: This is the jar I want to compile:

hadoop-mapreduce-examples-2.2.0-test-sources.jar.

I did jar xvf hadoop-mapreduce-examples-2.2.0-test-sources.jar to extract everything.

I now have

    ls
    META-INF    org

    ls org/apache/hadoop/
examples    mapreduce

    ls org/apache/hadoop/examples/
TestBaileyBorweinPlouffe.java   TestWordStats.java      pi              terasort

As you can notice, I have two packages within org.apache.hadoop, "examples and mapreduce", both of which have to be compiled. And I have sub-packages within "examples" that needs to be compiled.

javac org/apache/hadoop/mapreduce/lib/db/TestDBJob.java

This compiled fine

But How can I compile recursively. I tried using wildcard '*'.

This is what I tried:

javac -cp org/apache/hadoop/examples/*
javac: invalid flag: org/apache/hadoop/examples/pi
Usage: javac <options> <source files>
use -help for a list of possible options
javac org/apache/hadoop/examples/*.*

In the last javac executed above, I don't see the subpackages being compiled. only the top-level java files was compiled.

Is there a simple solution such as

javac -jar <input.jar> <output.jar> will result in <output-jar> that has compiled files in it.

EDIT:

To re-iterate my question:

given a jar that has only .java files, I want a jar file that has .class files in the simplest possible way

August answered 14/8, 2014 at 21:9 Comment(2)
Is there no Ant or Maven build file included?Interpose
Did you ever get an answer for this?Experience
A
0

From the DOS console

cd /dir/folder of .class files.

jar cvf name.jar

Assess answered 14/8, 2014 at 21:17 Comment(1)
I know that. That is not my question. given a jar that has only .java files, I want a jar file that has .class files.August
I
0

Here's a really dirty script I wrote to build compiled JAR out of a sources JAR. It probably won't work for everything, and doesn't even handle copying the Manifest:

#!/bin/bash

if [ "$#" -lt 1 ]; then
    echo "Usage: $0 sources.jar [classpath]"
    echo
    exit 1
fi

OUT_JAR=`basename $1-compiled.jar`

rm -rf $OUT_JAR
rm -rf src
rm -rf classes

mkdir src
mkdir classes

if [ -n "$2" ]; then
  CLASSPATH="-cp $2"
fi

unzip -d src $1
if [ $? -ne 0 ]; then
  echo "Unzip failed"
  exit 1
fi

find src -name *.java | xargs javac -d classes $CLASSPATH
if [ $? -ne 0 ]; then
  echo "Java compilation failed"
  exit 1
fi

jar cf $OUT_JAR -C classes .

if [ $? -ne 0 ]; then
  echo "Jar creation failed"
  exit 1
fi

echo
echo "Compiled and built $OUT_JAR"

Also available here: https://github.com/satur9nine/sources-jar-compiler/blob/master/compile-sources-jar.sh

Impressionism answered 27/8, 2020 at 18:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.