tags:

views:

164

answers:

2

This is annoying.

I have a directory structure like this

-lib
   --some jar files

-packageName
   --Main.java
   --SomeOtherPackage
      --SomeOtherJavaClass.java

Main.java imports SomeOtherPackage. And both java files uses jars in the lib.

What I do is add the jar files independently in the CLASSPATH. And then run as: javac packageName/Main.java

but it gives the error that Package not found SomeOtherPackage . Shouldn't it automatically realize the dependency and build SomeOtherPackage as well? What would be the javac command and the classpath for the above case?

Thanks

A: 

You need to add packageName to the CLASSPATH so it can find SomeOtherPackage

Chris Dodd
Ahan, that means I need to add all the sub-directories/sub-packages in the CLASSPATH ..isn't that a bit too tedious?
nEEbz
No, you just need to add all the directories that contain top-level package directories. Since SomeOtherPackage is NOT a sub-package of packageName, you need to add the directory that contains SomeOtherPackage directly
Chris Dodd
+1  A: 

The normal practice is to add the package root to the classpath.

When you're already in the package root, use -cp .. E.g.

cd /path/to/all/packages
javac -cp . packageName/Main.java

If you want to include JAR files as well, use the ; (or in *nix, the :) as classpath path separator:

javac -cp .;lib/file.jar packageName/Main.java

To save the time in repeating all the typing of shell commands, use a .bat (or in *nix a .sh) file. Or just an IDE if you're already familiar with java/javac and so on.

BalusC
This is the best way to go. However, it will not work unless you change your import line to be import packageName.SomeOtherPackage; Typically, if two packages are not to be built in the same project then they should have different root directories. In other words you should have src/packageName and src/SomeOtherPackage and then put src/packageName and src/SomeOtherPackage in your classpath. If they are in the same project then you should modify your import statement to reflect that. Import statements should always be absolute paths starting from your source code root.
Pace
Ok it worked. I ran javac -cp.;lib/<the jar files> packageName/Main.javabut it only created .class file of Main.java and didn't do anything with SomeOtherPackage.As I mentioned in the question, shouldn't it find the dependencies itself and create their classes?
nEEbz
I don't think so. It will only compile the given .java file. If you want to compile your entire project it may be time to switch to Ant but there are ways to specify multiple source files.
Pace
Indeed, to compile/build multiple classes, rather use a tool like ant or an IDE like Eclipse/IntelliJ/Netbeans.
BalusC