Sunday, August 1, 2010

A few words about classpaths.

Perfect, so here we are - classpaths. The topic that nearly every programmer had a contact with but some have very shallow knowledge about them. That's why I'll recap this subject.
All right, so what actually are the classpaths? The classpaths are the directories that 'java' and 'javac' look inside, in order to find the classes that are necessary to proceed with current operations. A note: classpaths are not the only places where 'java' and 'javac' look in. Before the standard directories of JSE are searched through.

The syntax of it is as follows:

 -classpath /com/foo/bar:/com/foo2/bar:bar/foo

And now some important things:

In the above example, the Unix syntax was used as for the path directories. In the windows we will have to use something like C:\ (or other drive) and afterwards the backslashes (\).

The next thing worth mentioning is the order. The classpaths are searched from left to right so if the class that we are looking for is both in /com/foo/bar and /com/foo2/bar then we can get different results when using this two options:

 -classpath /com/foo/bar:/com/foo2/bar:bar/foo
-classpath /com/foo2/bar:/com/foo/bar:bar/foo

Ok, now we will talk about the current directory. You see, in both of the above examples the current directory is not searched! Yes, it's not searched for the .class files! I mean, if you simply invoke 'javac' with some .java file it's no problem. But as for the .class files it's just not searched. To change it, we have to add a current directory to the classpath which is denoted by a dot (.). Here is a modified previous example:

 -classpath /com/foo/bar:/com/foo2/bar:bar/foo:.

As simple as that! Never forget to add the . if the current directory has to be searched!

Also please note that there is a distinction between absolute and relative classpaths. Absolute classpath in Unix will start with a slash and doesn't matter the directory it is used from, the effect will always be the same. In case of relative classpath the effect won't be the same since the current directory is treated as a root directory for it, so if run from the wrong directory mostly the attempt will fail due to the fact that class can't be found.

The last thing that I would like to mention about the classpaths are the JAR files. In comparison to the the class files, we have to add a name of the JAR file that we want to use. So let's say that a my.JAR file is located in /com/foo/bar. To make the actual use of it we have to modify our previous example to:

 -classpath /com/foo/bar:/com/foo2/bar:bar/foo:.:/com/foo/bar/my.JAR

That's a bunch of useful information, isn't it? Yeah, stay tuned! There will be much more in the next articles!

No comments:

Post a Comment