Java - How Classpath works in Java

转载 2015年07月07日 09:43:36

http://javarevisited.blogspot.de/2011/01/how-classpath-work-in-java.html

Sometimes I can't open this page without proper proxy configuration, so I have to copy the content here.


What is CLASSPATH in Java

Classpath in Java is path to directory or list of directory which is used by ClassLoaders to find and load class in Java program. Classpath can be specified using CLASSPATH environment variable which is case insensitive, -cp or -classpath command line option or Class-Path attribute in manifest.mf file inside JAR file in Java.

Don't confuse Classpath with PATH in Java, which is another environment variable used to find java binaries located in JDK installation directory, also known as JAVA_HOME. Main difference between PATH and CLASSPATH is that former is used to locate Java commands while later is used to locate Java class files.

Setting Java Classpath in Windows

In order to set Classpath for Java in Windows (any version either Windows XP,  Windows 2000 or Windows 7) ,you need to specify value of environment variable CLASSPATH, name of this variable is not case sensitive and it doesn’t matter if name of your environment variable is Classpath, CLASSPATH or classpath in Java.

  
1) open Environment variable window
2)  specify your environment variable CLASSPATH and put the value of your JAVA_HOME\lib and also include current directory by including (dot or period sign).
3)  Now to check the value of Java classpath in windows type "echo %CLASSPATH%" in your DOS command prompt and it will show you the value of directory which are included in CLASSPATH.

Setting Java Classpath in UNIX or Linux

To set Classpath for Java In Linux you can simply add "export CLASSPATH="your classpath" " to either your .bash_profile or .bashrc script which will run whenever you login into your Linux or Unix Machine.

Type "echo ${CLASSPATH}" to check value of Java CLASSPATH in Linux.

Overriding Classpath in Java

You can override classpath by providing option "-cp" or "-classpath" while running Java program. This is the best way to have different classpath for different Java application running on same Unix or Windows machine. standard way to define classpath for Java application is creating start-up script for Java program and set classpath there as shown below :

CLASSPATH=/home/tester/classes
java -cp $CLASSPATH Test

By default Java CLASSPATH points to current directory denoted by "." and it will look for any class only in current directory.

In case you have multiple directories defined in CLASSPATH variable, Java will look for a class starting from first directory and only look second directory in case it did not find the specified class in first directory.

I have used this feature of Java Classpath to test my patch releases. We used to have a folder called "patch" listed as first element in Java CLASSPATH and any point of time we want to put any debug statement or want to test any bug we just modify Java source file , compile it and generate class file and put that inside patch folder instead of creating JAR file and releasing whole new Java application. This is very handy if you are working in a large project where you don't have development environment setup in Windows and your project only runs on Unix server. This approach is much faster than remote debugging Java application in Eclipse

It's also worth noting that when you use the  java -jar command line option to run your Java program as an executable JAR, then the CLASSPATH environment variable will be ignored, and also the -cp and -classpath switches will be ignored. In this case you can set your Java classpath in the META-INF/MANIFEST.MF file by using the Class-Path attribute. In short, Class-path attribute in manifest file overrides classpath specified by -cp, -classpath or CLASSPATH environment variable.


Now a common question if I have my CLASSPATH variable pointing to current directory "." and I have class called "Test" inside package "testing" and with below directory structure C:\project\testing\Test.class in my computer.

What will happen if I run command "java Test" from directory "C:\project\testing\"? will it run?
No, it will not run it will give you :
Exception in thread "main" java.lang.NoClassDefFoundError: Test
Since name of the class is not Test, instead it’s testing.Test even though your classpath is set to current directory.

Now what will happen if I give command  java testing.Test from C:\project\testing\ it will again not run and give error?

Exception in thread "main" java.lang.NoClassDefFoundError: testing/Test

Why because now it looking for class called Test which is in package testing, starting from current directory "." but don't find it since there is no directory called "testing after this path "C:\project\testing\".

To run it successfully you need to go back to directory  C:\project and now run
C:\project>java testing.Test  and It will run successfully.
Because of Classpath issues I prefer to use Eclipse rather than running Java program from command prompt.


Errors related to Classpath in Java

If you are working in Java you must have faced some errors and exception related to classpath in java, two most common issues related to java classpath is ClassNotFoundException and NoClassDefFoundError.

Here is the reason of these Java classpath errors :

ClassNotFoundException is an Exception and will be thrown when Java program dynamically tries to load a Java class at Runtime and don’t find corresponding class file on classpath. Two keyword here “dynamically” and “runtime”. Classic example of these errors is whey you try to load JDBC driver by using Class.forname(“driver name”) and greeted with java.lang.ClassNotFoundException: com.mysql.jdbc.Driver. So this error essentially comes when Java try to load a class using forName() or by loadClass() method of ClassLoader. Key thing to note is that presence of that class on Java classpath is not checked on compile time. So even if those classes are not present on Java classpath your program will compile successfully and only fail when you try to run.

On the other hand NoClassDefFoundError is an Error and more critical than ClassNotFoundException. NoClassDefFoundError comes when a particular class was present in Java Classpath during compile time but not available during run-time. Classic example of this error is using log4j.jar for logging purpose and forgot to include log4j.jar on classpath in java during run-time. Keyword here is,  class was present at compile time but not available on run-time.  This is normally occurring due to any method invocation on a particular class which is part of library and not available on classpath in Java.

Summary of CLASSPATH in Java

1. Classpath in Java is an environment variable used by Java Virtual machine to locate or find  class files in Java during class loading.

2. You can override value of Classpath in Java defined by environment variable CLASSPATH by providing JVM command line option –cp or –classpath while running your application.

3. If two classes with same name exist in Java Classpath then the class which comes earlier in Classpath will be picked by Java Virtual Machine.

4. By default CLASSPATH in Java points to current directory denoted by "." and it will look for any class only in current directory.

5. When you use the -jar command line  option to run your program as an executable JAR, then the Java CLASSPATH environment variable will be ignored, and also the -cp and -classpath switches will be ignored and In this case you can set your java classpath in the META-INF/MANIFEST.MF file by using the Class-Path attribute.

6. In Unix of Linux Java Classpath contains names of directory with colon “:” separated , On Windows Java Classpath will be  semi colon “;” separated while if you defined java classpath in Manifest file those will be space separated.

7. You can check value of classpath in java inside your application by looking at following system property “java.class.path”  System.getProperty("java.class.path")

Class-Path attribute is used to contain classpath inside manifest file. Also make sure that your manifest file must end with a blank line (carriage return or new line) , here is an example of java classpath in manifest file.

Main-Class: com.classpathexample.Demo_Classpath
Class-Path: lib/tibco.jar lib/log4j.jar

8. It’s also important to note that path specified in manifest file is not absolute instead they are relative from application jar’s path. For example in above if your application jar file is in C:\test directory you must need a lib directory inside test and tibco.jar and log4j.jar inside that.

9. ClassNotFoundException is an Exception and will be thrown when Java program dynamically tries to load a particular Class at Runtime and don’t find that on Java classpath due to result of Class.forName() or loadClass() method invocation.

10. NoClassDefFoundError comes when a particular class was present in Java Classpath during compile time but not available during runtime on Classpath in Java.


《how tomcat works》翻译开篇

《how tomcat work》翻译此书只为学习,有错误,不到位之处,请指出。文笔欠佳,请多海涵。简介概述欢迎来到《how tomcat works》,这本书剖析了当下免费的 ,开源的,并且是最为流...
  • tomcat_how_work
  • tomcat_how_work
  • 2015年11月01日 23:26
  • 659

探索《How Tomcat Works》心得(一)

很久之前就开始对Tomcat感兴趣,于是开始查询如何学习Tomcat,发现论坛里好多的观点都说,《How Tomcat Works》是学习Tomcat的必备书籍。于是自己开始学习这本书。看这本书到现在...
  • u012561308
  • u012561308
  • 2016年05月02日 11:01
  • 471

运行Java程序-设置classpath

Java命令用于运行Java程序,它会启动Java虚拟机,Java虚拟机加载相关的类,然后调用主程序类的mail()fan...
  • zhangminemail
  • zhangminemail
  • 2014年05月02日 16:23
  • 985

java命令行下如何设置classpath类路径

以往基于构建工具和IDE工作,很少使用命令行执行程序,但偶尔使用命令行的时候关于类路径的设置都要查阅一下说明文档,这里找到一个详尽清晰的说明,以备自查.特别指明的是:classpath一定要使用""(...
  • bluishglc
  • bluishglc
  • 2013年08月14日 22:50
  • 63163

java中path和CLASSPATH的配置和意义解析

一、jdk中的jre和java目录下的jre文件的内容区别; 二、环境变量的设置; 三、path和CLASSPATH路径设置的意义和区别; 四、环境变量与系统环境变量的区别;...
  • eclipse_yin
  • eclipse_yin
  • 2016年05月18日 20:45
  • 3553

Java代码获取classpath路径方法和资源文件的读取方法

classpath 是什么?简单从字面分析看 class path,即类路径,其实就是这个意思,Java程序工作时靠的是各种Java 类来进行工作,那这些工作类存放在哪里呢?这是个重要问题,一个Jav...
  • shenzhenNBA
  • shenzhenNBA
  • 2016年09月03日 01:05
  • 5834

Java中关于package和classpath的总结

转载自:http://blog.sina.com.cn/s/blog_533074eb01014yd7.html package中所存放的文件   所有文件,不过一般分一下就分这三种 ...
  • u012179540
  • u012179540
  • 2014年12月28日 14:57
  • 2039

java命令行运行设置classpath星号的作用

java classpath 和 classpath引入和不引入星号(*) 区别:  classpath 不引入星号:如:D:\abc\ 只会到你的class路径中查找找文件;  classpath...
  • caomiao2006
  • caomiao2006
  • 2016年06月10日 18:50
  • 3507

《How Tomcat Works》读书笔记(一)

本系列来源于:http://blog.csdn.net/wangchengsi/article/details/3981861   看了这本书的头三章,写得非常好,可谓深入浅出将tomcat分析的...
  • cbjcry
  • cbjcry
  • 2017年04月13日 11:13
  • 86

java classpath如何指定一个目录及java资源文件的路径查找问题

一、资源文件的路径查找 当我们自己的程序需要处理配置文件时(比如xml文件或properties文件),通常会遇到两个问题:   (1)我的配置文件应该放在哪里?   (2)怎么我的...
  • salonhuang
  • salonhuang
  • 2017年07月07日 15:20
  • 1870
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Java - How Classpath works in Java
举报原因:
原因补充:

(最多只允许输入30个字)