Say I have a jar1 which has some classes that are a central set of classes with 0 dependencies. I then have another set of java files that depends on some of the jar1 classes to compile. I would like to create a jar2 that doesn't also contain the jar1 code so I don't end up duplicating code between jar1 and jar2. I will be giving out both jar1 and jar2 to consumers, jar1 would work independently but jar2 needs jar 1. If I don't include jar1 while compiling jar2 the compiler cries obviously. Can I just instead ship the raw .java files in the jar2 so the compiling is done only on importing into the app which will have loaded jar1?
I going to rephrase what (I think) you are asking.
You have a collection of Java source classes (e.g. a "library" or "project") that are the core of your application suite (or something like that). You want to create a second collection of Java source classes that depend on the first collection that form the "application".
You don't want the second collection to contain copies of the source code of the first one. Naturally.
This is all standard stuff.
So you compile the first collection and create a JAR file (lets call it "library.jar") from the compiled classes.
Then you compile the second collection, including the "library.jar" file on the compile-time classpath. Then create a second JAR file (lets call it "application.jar") containing the compiled versions of the second collection's classes.
So now we have two JAR files which do NOT contain duplicate code. You would typically run them like this:
java -classpath application.jar:library.jar some.pkg.MyMain ....
So you say that that compiling the second collection is not working for you. The compiler is complaining about not being able to find the classes in your first collection.
Most likely, that is because you forgot to include the "library.jar" file on the compile time classpath. Like this
javac -classpath library.jar ....
Note that there are Java build tools that can take care of a lot of this for you so that you don't have to run javac
and jar
and other things by hand. In the Android world, the preferred build tool is Gradle. Do some reading on what it can do.
I guess that you could use Make / CMake, but CMake's support for Java seems rather primitive compared to a Java build tool.
Can I just instead ship the raw .java files in the jar2 so the compiling is done only on importing into the app which will have loaded jar1?
You shouldn't need to do that. All you need to do is to correct the problem with the way you are compiling.
The flip-side is that Java source code is not automatically compiled by importing it. (Java is not a scripting language ...) If you ship source code to an end user, you will also need provide them with build instructions, scripts, whatever. If the people you are shipping code to are not programmers, that's a bad idea.