Search code examples
javacompilationjavac

Javac does compiling always have to be from top of package? (Passing path of package to javac ?)


When compiling java code the I have been told the compiler must be run from the top of the package.

That is if I am trying to compile Test.java which is in tools.testing I have to first set the top of the package hierarchy, the folder containing /tools in order for it to work.

The class I am trying to compile uses another class contained in the same package and as such passing the full path of the code to the compiler prevents it from seeing the other class (as it doesn't search current directory and instead searches for the package inside of itself: ./tools/testing when it is already in /tools/testing )

I wanted to know if this was always the case or if there was a way to, for example: provide the path to the top of the package (since passing full path will not work for me) as an argument of the javac command or something similar ?

Thanks !


Solution

  • You should use an Integrated Development Environment (IDE) like IntelliJ, Eclipse or Netbeans. In an IDE you can create a Java project which has a directory acting as the 'source root'.

    If you use Maven as your build tool the default location for such a directory is /src/main/java/ (this is the de-facto standard for Java projects at this time).

    The IDE will automatically compile your Java files for you and allow you to run them easily during development.

    If you want to run the application stand-alone you have to package it in some way. One simple and effective way is to generate a .jar file which contains all the .class files and other files you need (like images, .properties files etc). If you specify a pom.xml file for your project (that's Maven again) and set the packaging to jar Maven will automatically create a .jar file for you. You can even make the .jar file runnable with some additional settings.

    See also this answer for some more info about packaging.