Что такое classpath в java
Перейти к содержимому

Что такое classpath в java

  • автор:

Кофе-брейк #121. Что такое Classpath в Java и как его установить? Неизменяемость в Java

Java-университет

Кофе-брейк #121. Что такое Classpath в Java и как его установить? Неизменяемость в Java - 1

Источник: Medium Знание основ программирования и потока выполнения программных файлов помогает нам понять язык. Знание параметра Classpath — одно из основных понятий, которым должен владеть каждый Java-разработчик. Сегодня мы обсудим, что такое путь к классам ( Classpath ), как его установить и как он помогает JVM исполнять файлы классов.

Что такое Classpath?

Classpath является одним из основных параметров в Java, однако новички в программировании часто понимают его неправильно. Если упростить, то Classpath — это просто набор путей , по которым компилятор Java и JVM должны находить необходимые классы для компиляции или выполнения других классов.

Как Classpath помогает JVM в выполнении файлов классов

Давайте начнем с примера. Предположим, что у нас есть файл Main.java , который находится в папке /Users/vikram/Documents/test-java/src/com/programming/v1/Main.java.

 package com.programming.v1; public class Main < public static void main(String[] args) < System.out.println("Hello classpath"); >> 

Допустим, мы находимся в /Users/vikram/Documents и хотим скомпилировать этот класс:

 javac test-java/src/com/programming/v1/Main.java 

Теперь, чтобы выполнить этот файл класса, нам нужно сообщить виртуальной машине Java, где искать файл .class , используя classpath или флаг cp в команде java .

 vg@lp1 Documents % java -cp "test-java/src" com.programming.v1.Main Hello classpath vg@lp1 Documents % java -classpath "test-java/src" com.programming.v1.Main Hello classpath 

Первый параметр — это корневая папка, в которую записывается пакет. Второй параметр — это имя пакета с именем класса. Когда команда Java исполняется, виртуальная машина Java просматривает папку test-java/src, а затем загружает основной класс для ее выполнения.

Как установить переменный Classpath

Переменный параметр Classpath может быть установлен, как показано ниже, на компьютерах под управлением Linux:

 export CLASSPATH="test-java/src" 

Classpath на компьютере с Windows можно добавить/обновить с помощью переменных среды. После того, как переменная среды установлена, команду java можно выполнить, как показано ниже:

 vg@lp1 Documents % java com.programming.v1.Main Hello classpath 

Вот и все, что нужно знать о Classpath . Спасибо за чтение!

Неизменяемость в Java

Кофе-брейк #121. Что такое Classpath в Java и как его установить? Неизменяемость в Java - 2

Источник: Medium Переменные в Java бывают двух типов: примитивные и ссылочные. Все в Java передается по значению, но в случае ссылочных типов исходные данные могут обновляться с использованием переданного адреса памяти. Ключевое слово final используется для того, чтобы переменная действовала как константа, то есть избегала переназначения. Это хорошо работает для примитивов, у которых нет памяти в куче, тогда как для ссылочных типов ограничено только переназначение, а внутреннее состояние может быть изменено. Это может привести к множеству проблем с параллелизмом и условиям гонки (race conditions). Таким образом включение неизменяемых характеристик в обычный тип в Java дает много преимуществ.

Преимущества неизменяемости в Java

1. Безопасность потоков

Неизменяемые типы невосприимчивы к условиям гонки в многопоточной среде, поскольку объект останется согласованным после его создания. Несколько потоков не могут изменить свое внутреннее состояние, поэтому синхронизация не требуется.

2. Основополагающий тип

String в стандартной библиотеке Java — хороший пример базового класса. Это очень простой и неизменяемый класс, который можно использовать для создания доменов бизнес-логики поверх него. Точно так же неизменяемый тип может выступать в качестве отличного базового типа, на основе которого можно строить.

Характеристики

1. Поля Private и Final

Поля, содержащие состояние объекта, — это private и final . Частная ( private ) видимость запрещает прямой доступ к полю, а окончательная ( final ) гарантирует, что поле назначается только один раз.

2. Никаких методов-модификаторов

К полю private нельзя получить доступ за пределами класса. Обычно для чтения и записи в поля предусмотрены методы доступа (геттеры) и методы-модификаторы (сеттеры) соответственно. Для обеспечения неизменности модификаторы не допускаются.

3. Класс Final

Предоставление возможности наследования класса может нарушить неизменяемость. Подкласс, расширяющий неизменяемый класс, может повлиять на состояние объекта. Следовательно, класс является окончательным ( final ).

4. Защитные копии (Defensive Copies)

Во время создания объекта вместо того, чтобы назначать аргументы из конструктора непосредственно закрытым полям, создание глубокой копии (или неизменяемой копии) аргументов обеспечит внешнее изменение. Если один из аргументов является ссылочным типом, им можно легко манипулировать на вызывающей стороне. Создание защитных копий позволяет избежать этой манипуляции. Точно так же для средств доступа (геттеров) вместо прямой ссылки на внутреннее поле можно свободно делиться его копией.

Реализация

Employee
 import java.time.LocalDate; import java.util.List; import static java.util.List.copyOf; public final class Employee < private final long id; private final String name; private final LocalDate joinDate; private final Listachievements; public Employee(long id, String name, LocalDate joinDate, List achievements) < this.id = id; this.name = name; this.joinDate = joinDate; this.achievements = copyOf(achievements); >public long getId() < return id; >public String getName() < return name; >public LocalDate getJoinDate() < return joinDate; >public List getAchievements() < return achievements; >> 
  • Не все поля имеют защитные копии в конструкторе. Это связано с тем, что id является примитивным, а поля name и joinDate являются неизменяемыми типами. Они не могут быть изменены вызывающей стороной и останутся неизменными, в то время как поле achievements требует копии аргумента, сделанного с помощью метода List.copyOf . Это объясняется тем, что copyOf возвращает неизменяемый List .
  • Точно так же методы доступа возвращают поля напрямую, а не защитные копии, потому что все типы полей являются неизменяемыми (включая achievements ) и, следовательно, не могут быть изменены вне класса.

Улучшения

До Java 16

Реализация Employee может быть улучшена с помощью таких библиотек, как Lombok. Это уменьшает многословие в коде и помогает ему выглядеть более чистым. Библиотека поставляется с аннотациями для сокращения стандартного кода. @Value (аннотация) может использоваться для создания геттеров и конструктора всех аргументов. Это также создает класс final и поля private и final . В качестве примечания, он также генерирует методы toString , equals и hashCode . Реализация Employee может быть переписана с помощью @Value , как показано ниже:

 import lombok.Value; import java.time.LocalDate; import java.util.List; import static java.util.List.copyOf; @Value public class Employee < long id; String name; LocalDate joinDate; Listachievements; public Employee(long id, String name, LocalDate joinDate, List achievements) < this.id = id; this.name = name; this.joinDate = joinDate; this.achievements = copyOf(achievements); >> 

Java 16 и более поздние версии

В релизе Java 16 появилась новая функция Record . Она (как утверждает JEP) является классами, которые действуют как прозрачные носители неизменяемых данных и могут рассматриваться как номинальные кортежи (tuples). Класс Employee можно повторно реализовать как record Employee , что показано ниже.

 import java.time.LocalDate; import java.util.List; import static java.util.List.copyOf; public record Employee(long id, String name, LocalDate joinDate, List achievements) < public Employee(long id, String name, LocalDate joinDate, Listachievements) < this.id = id; this.name = name; this.joinDate = joinDate; this.achievements = copyOf(achievements); >> 

Недостатки

Единственная проблема с неизменяемостью — дополнительная память и обработка, которые требуются даже для небольшой модификации. Каждый раз необходимо создавать новый объект, что может быть весьма накладно. Чтобы обойти этот недостаток, можно реализовать такие механизмы, как кэширование и сохранение результатов.

What is a classpath and how do I set it?

When programming in Java, you make other classes available to the class you are writing by putting something like this at the top of your source file:

import org.javaguy.coolframework.MyClass; 

Or sometimes you ‘bulk import’ stuff by saying:

import org.javaguy.coolframework.*; 

So later in your program when you say:

MyClass mine = new MyClass(); 

The Java Virtual Machine will know where to find your compiled class.

It would be impractical to have the VM look through every folder on your machine, so you have to provide the VM a list of places to look. This is done by putting folder and jar files on your classpath.

Before we talk about how the classpath is set, let’s talk about .class files, packages, and .jar files.

First, let’s suppose that MyClass is something you built as part of your project, and it is in a directory in your project called output . The .class file would be at output/org/javaguy/coolframework/MyClass.class (along with every other file in that package). In order to get to that file, your path would simply need to contain the folder ‘output’, not the whole package structure, since your import statement provides all that information to the VM.

Now let’s suppose that you bundle CoolFramework up into a .jar file, and put that CoolFramework.jar into a lib directory in your project. You would now need to put lib/CoolFramework.jar into your classpath. The VM will look inside the jar file for the org/javaguy/coolframework part, and find your class.

So, classpaths contain:

  • JAR files, and
  • Paths to the top of package hierarchies.

How do you set your classpath?

The first way everyone seems to learn is with environment variables. On a unix machine, you can say something like:

export CLASSPATH=/home/myaccount/myproject/lib/CoolFramework.jar:/home/myaccount/myproject/output/ 

On a Windows machine you have to go to your environment settings and either add or modify the value that is already there.

The second way is to use the -cp parameter when starting Java, like this:

java -cp "/home/myaccount/myproject/lib/CoolFramework.jar:/home/myaccount/myproject/output/" MyMainClass 

A variant of this is the third way which is often done with a .sh or .bat file that calculates the classpath and passes it to Java via the -cp parameter.

There is a «gotcha» with all of the above. On most systems (Linux, Mac OS, UNIX, etc) the colon character (‘:’) is the classpath separator. In windowsm the separator is the semicolon (‘;’)

So what’s the best way to do it?

Setting stuff globally via environment variables is bad, generally for the same kinds of reasons that global variables are bad. You change the CLASSPATH environment variable so one program works, and you end up breaking another program.

The -cp is the way to go. I generally make sure my CLASSPATH environment variable is an empty string where I develop, whenever possible, so that I avoid global classpath issues (some tools aren’t happy when the global classpath is empty though — I know of two common, mega-thousand dollar licensed J2EE and Java servers that have this kind of issue with their command-line tools).

1,592 2 2 gold badges 12 12 silver badges 30 30 bronze badges
answered Mar 7, 2010 at 15:27
8,222 1 1 gold badge 17 17 silver badges 3 3 bronze badges
Another well explained blog on What is PATH and CLASSPATH in Java — Path vs ClassPath
Nov 20, 2014 at 8:50

In python there’s a folder called Lib where you can store any module to use at any time with a simple import statement. Is this different than setting the CLASSPATH environment variable to a directory for third-party java packages? Even though it would be global, there would be no need to change the variable, other than adding more packages.

Jun 22, 2016 at 8:36

Nice answer, but for the dummies out here: Why do you not need to use the -cp command for every new class you create? This surely is solved automatically by your system right? But how? I sometimes encounter a problem where «something» can not be found in my classpath — I guess it is so because I didn’t add it to the cp, but why does such an error occur only sometimes instead of always? I ask this because, to be honest, I didn’t ever include anything manually with the -cp command and would not know what to do with an error like that

Jan 26, 2017 at 8:48

@Vic The classpath needs to contain the directory above the directory hierarchy corrresponding to the package name. So if I have org.javaguy.coolfw , with corresponding directory structure /path/to/org/javaguy/coolfw/ , the classpath would need to contain /path/to/ . If I add a new package org.javaguy.hotfw in the same project, the resulting class (usually) ends up at /path/to/org/javaguy/hotfw/ . This requires the classpath to contain /path/to/ , which it already does. So the new package (and classes contained therein) don’t require new additions to the classpath.

Aug 24, 2017 at 16:49

@Vic For a more concrete example and explanation, see Mastering the Java CLASSPATH (per KNU’s excellent comment)

Aug 24, 2017 at 16:51

Think of it as Java’s answer to the PATH environment variable — OSes search for EXEs on the PATH, Java searches for classes and packages on the classpath.

703k 95 95 gold badges 819 819 silver badges 1223 1223 bronze badges
answered Mar 7, 2010 at 14:10
user257111 user257111

except that path is Completely Optional while classpath is mandatory—Java has no support for absolute names.

Sep 18, 2022 at 23:45

Not every OS searches for necessarily EXEs. This answer can be made better by changing «EXEs» to «executable binaries».

Dec 3, 2022 at 22:25

The classpath is one of the fundamental concepts in the Java world and it’s often misunderstood or not understood at all by java programmes, especially beginners.

Simply put, the classpath is just a set of paths where the java compiler and the JVM must find needed classes to compile or execute other classes.

Let’s start with an example, suppose we have a Main.java file thats under C:\Users\HP\Desktop\org\example ,

package org.example; public class Main < public static void main(String[] args) < System.out.println("Hello world"); >> 

And Now, suppose we are under C:\ directory and we want to compile our class, Its easy right, just run:

javac .\Users\HP\Desktop\org\example\Main.java 

Now for the hard question, we are in the same folder C:\ and we want to run the compiled class.

Despite of what you might think of to be the answer, the right one is:

java -cp .\Users\HP\Desktop org.example.Main 

I’ll explain why, first of all, the name of the class that we want ro tun is org.exmaple.Main not Main, or Main.class or .\users\hp\desktop\org\example\Main.class ! This is how things works with classes declared under packages.

Now, we provided the name of the class to the JVM (java command in this case), But how it (JVM) will know where to find the .class file for the Main class? Thats where the classpath comes into picture. Using -cp flag (shortcut for -classpath), we tell the JVM that our Main.class file will be located at C:\users\hp\Desktop .. In fact, not really, we tell it to just go to the Desktop directory, and, because of the name of the class org.example.Main, the JVM is smart and it will go from Desktop to org directory, and from org to example directory, searching for Main.class file , and it will find it and it will kill it, I mean, it will run it 😀 .

Now lets suppose that inside the Main class we want to work with another class named org.apache.commons.lang3.StringUtils and the latter is located in a jar file named commons-lang3-3.10.jar thats inside C:\Users\HP\Downloads . So Main.java will look like this now:

package org.example; import org.apache.commons.lang3.StringUtils; public class Main < public static void main(String[] args) < System.out.println("Hello world"); System.out.println(StringUtils.equals("java", "java")); //true >> 

How to compile the Main.java if we are always inside C:\ ? The answer is:

javac -cp .\Users\HP\Downloads\commons-lang3-3.10.jar .\Users\HP\Desktop\org\example\Main.java 
  • .\Users\HP\Desktop\org\example\Main.java is because our .java file is there in the filesystem.
  • -cp .\Users\HP\Downloads\commons-lang3-3.10.jar is because the java compiler (javac in this case) need to know the location of the class org.apache.commons.lang3.StringUtils, so we provided the path of the jar file, and the compiler will then go inside the jar file and try to find a file StringUtils.class inside a directory org\apache\commons\lang3 .

And if we want to run the Main.class file, we will execute:

java -cp ".\Users\HP\Desktop\;.\Users\HP\Downloads\commons-lang3-3.10.jar" org.example.Main 
  • org.example.Main is the name of the class.
  • «.\Users\HP\Desktop\;.\Users\HP\Downloads\commons-lang3-3.10.jar» are the paths (separated by ; in Windows) to the Main and StringUtils classes.

PATH and CLASSPATH

This section explains how to use the PATH and CLASSPATH environment variables on Microsoft Windows, Solaris, and Linux. Consult the installation instructions included with your installation of the Java Development Kit (JDK) software bundle for current information.

After installing the software, the JDK directory will have the structure shown below.

The bin directory contains both the compiler and the launcher.

Update the PATH Environment Variable (Microsoft Windows)

You can run Java applications just fine without setting the PATH environment variable. Or, you can optionally set it as a convenience.

Set the PATH environment variable if you want to be able to conveniently run the executables ( javac.exe , java.exe , javadoc.exe , and so on) from any directory without having to type the full path of the command. If you do not set the PATH variable, you need to specify the full path to the executable every time you run it, such as:

C:\Java\jdk1.7.0\bin\javac MyClass.java

The PATH environment variable is a series of directories separated by semicolons ( ; ). Microsoft Windows looks for programs in the PATH directories in order, from left to right. You should have only one bin directory for the JDK in the path at a time (those following the first are ignored), so if one is already present, you can update that particular entry.

The following is an example of a PATH environment variable:

C:\Java\jdk1.7.0\bin;C:\Windows\System32\;C:\Windows\;C:\Windows\System32\Wbem

It is useful to set the PATH environment variable permanently so it will persist after rebooting. To make a permanent change to the PATH variable, use the System icon in the Control Panel. The precise procedure varies depending on the version of Windows:

  1. Select Start, select Control Panel. double click System, and select the Advanced tab.
  2. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New .
  3. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
  1. From the desktop, right click the My Computer icon.
  2. Choose Properties from the context menu.
  3. Click the Advanced tab (Advanced system settings link in Vista).
  4. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New .
  5. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
  1. From the desktop, right click the Computer icon.
  2. Choose Properties from the context menu.
  3. Click the Advanced system settings link.
  4. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New .
  5. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.

Note: You may see a PATH environment variable similar to the following when editing it from the Control Panel:

%JAVA_HOME%\bin;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem

Variables enclosed in percentage signs ( % ) are existing environment variables. If one of these variables is listed in the Environment Variables window from the Control Panel (such as JAVA_HOME ), then you can edit its value. If it does not appear, then it is a special environment variable that the operating system has defined. For example, SystemRoot is the location of the Microsoft Windows system folder. To obtain the value of a environment variable, enter the following at a command prompt. (This example obtains the value of the SystemRoot environment variable):

echo %SystemRoot%

Update the PATH Variable (Solaris and Linux)

You can run the JDK just fine without setting the PATH variable, or you can optionally set it as a convenience. However, you should set the path variable if you want to be able to run the executables ( javac , java , javadoc , and so on) from any directory without having to type the full path of the command. If you do not set the PATH variable, you need to specify the full path to the executable every time you run it, such as:

% /usr/local/jdk1.7.0/bin/javac MyClass.java

To find out if the path is properly set, execute:

% java -version

This will print the version of the java tool, if it can find it. If the version is old or you get the error java: Command not found, then the path is not properly set.

To set the path permanently, set the path in your startup file.

For C shell ( csh ), edit the startup file (~/.cshrc ):

set path=(/usr/local/jdk1.7.0/bin $path)

For bash , edit the startup file ( ~/.bashrc ):

PATH=/usr/local/jdk1.7.0/bin:$PATH export PATH

For ksh , the startup file is named by the environment variable, ENV . To set the path:

PATH=/usr/local/jdk1.7.0/bin:$PATH export PATH

For sh , edit the profile file ( ~/.profile ):

PATH=/usr/local/jdk1.7.0/bin:$PATH export PATH

Then load the startup file and verify that the path is set by repeating the java command:

For C shell ( csh ):

% source ~/.cshrc % java -version

For ksh , bash , or sh :

% . /.profile % java -version

Checking the CLASSPATH variable (All platforms)

The CLASSPATH variable is one way to tell applications, including the JDK tools, where to look for user classes. (Classes that are part of the JRE, JDK platform, and extensions should be defined through other means, such as the bootstrap class path or the extensions directory.)

The preferred way to specify the class path is by using the -cp command line switch. This allows the CLASSPATH to be set individually for each application without affecting other applications. Setting the CLASSPATH can be tricky and should be performed with care.

The default value of the class path is «.», meaning that only the current directory is searched. Specifying either the CLASSPATH variable or the -cp command line switch overrides this value.

To check whether CLASSPATH is set on Microsoft Windows NT/2000/XP, execute the following:

C:> echo %CLASSPATH%

On Solaris or Linux, execute the following:

% echo $CLASSPATH

If CLASSPATH is not set you will get a CLASSPATH: Undefined variable error (Solaris or Linux) or simply %CLASSPATH% (Microsoft Windows NT/2000/XP).

To modify the CLASSPATH , use the same procedure you used for the PATH variable.

Class path wildcards allow you to include an entire directory of .jar files in the class path without explicitly naming them individually. For more information, including an explanation of class path wildcards, and a detailed description on how to clean up the CLASSPATH environment variable, see the Setting the Class Path technical note.

Previous page: Miscellaneous Methods in System
Next page: Questions and Exercises: The Platform Environment

2 Setting the Class Path

The class path is the path that the Java Runtime Environment (JRE) searches for classes and other resource files.

This chapter covers the following topics:

  • Synopsis
  • Description
  • JDK Commands Class Path Options
  • CLASSPATH Environment Variable
  • Class Path Wild Cards
  • Class Path and Package Names

Synopsis

The class search path (class path) can be set using either the -classpath option when calling a JDK tool (the preferred method) or by setting the CLASSPATH environment variable. The -classpath option is preferred because you can set it individually for each application without affecting other applications and without other applications modifying its value.

sdkTool -classpath classpath1;classpath2.

set CLASSPATH=classpath1;classpath2.

A command-line tool, such as java , javac , javadoc , or apt . For a listing, see JDK Tools and Utilities at
http://docs.oracle.com/javase/8/docs/technotes/tools/index.html

classpath1:classpath2

Class paths to the JAR, zip or class files. Each class path should end with a file name or directory depending on what you are setting the class path to, as follows:

  • For a JAR or zip file that contains class files, the class path ends with the name of the zip or JAR file.
  • For class files in an unnamed package, the class path ends with the directory that contains the class files.
  • For class files in a named package, the class path ends with the directory that contains the root package, which is the first package in the full package name.

Multiple path entries are separated by semicolons with no spaces around the equals sign (=) in Windows and colons in Oracle Solaris.

The default class path is the current directory. Setting the CLASSPATH variable or using the -classpath command-line option overrides that default, so if you want to include the current directory in the search path, then you must include a dot ( . ) in the new settings.

Class path entries that are neither directories nor archives (.zip or JAR files) nor the asterisk ( * ) wildcard character are ignored.

Description

The class path tells the JDK tools and applications where to find third-party and user-defined classes that are not extensions or part of the Java platform. See The Extension Mechanism at
http://docs.oracle.com/javase/8/docs/technotes/guides/extensions/index.html

The class path needs to find any classes you have compiled with the javac compiler. The default is the current directory to conveniently enable those classes to be found.

The JDK, the JVM and other JDK tools find classes by searching the Java platform (bootstrap) classes, any extension classes, and the class path, in that order. For details about the search strategy, see How Classes Are Found at
http://docs.oracle.com/javase/8/docs/technotes/tools/findingclasses.html

Class libraries for most applications use the extensions mechanism. You only need to set the class path when you want to load a class that is (a) not in the current directory or in any of its subdirectories, and (b) not in a location specified by the extensions mechanism.

If you upgrade from an earlier release of the JDK, then your startup settings might include CLASSPATH settings that are no longer needed. You should remove any settings that are not application-specific, such as classes.zip . Some third-party applications that use the Java Virtual Machine (JVM) can modify your CLASSPATH environment variable to include the libraries they use. Such settings can remain.

You can change the class path by using the -classpath or -cp option of some Java commands when you call the JVM or other JDK tools or by using the CLASSPATH environment variable. See JDK Commands Class Path Options. Using the -classpath option is preferred over setting the CLASSPATH environment variable because you can set it individually for each application without affecting other applications and without other applications modifying its value. See CLASSPATH Environment Variable.

Classes can be stored in directories (folders) or in archive files. The Java platform classes are stored in rt.jar. For more details about archives and information about how the class path works, see Class Path and Package Names.

Note: Some earlier releases of the JDK had a /classes entry in the default class path. That directory exists for use by the JDK software and should not be used for application classes. Application classes should be placed in a directory outside of the JDK directory hierarchy. That way, installing a new JDK does not force you to reinstall application classes. For compatibility with earlier releases, applications that use the /classes directory as a class library run in the current release, but there is no guarantee that they will run in future releases.

JDK Commands Class Path Options

The following commands have a -classpath option that replaces the path or paths specified by the CLASSPATH environment variable while the tool runs: java , jdb , javac , javah and jdeps .

The -classpath option is the recommended option for changing class path settings, because each application can have the class path it needs without interfering with any other application.The java command also has a -cp option that is an abbreviation for -classpath .

For very special cases, both the java and javac commands have options that let you change the path they use to find their own class libraries. Most users will never need to use those options.

CLASSPATH Environment Variable

As explained in JDK Commands Class Path Options, the -classpath command-line option is preferred over the CLASSPATH environment variable. However, if you decide to use the CLASSPATH environment variable, this section explains how to set and clear it.

Set CLASSPATH

The CLASSPATH environment variable is modified with the set command. The format is:

set CLASSPATH=path1;path2 .

The paths should begin with the letter specifying the drive, for example, C:\. That way, the classes will still be found if you happen to switch to a different drive. If the path entries start with backslash (\) and you are on drive D:, for example, then the classes will be expected on D:, rather than C:.

Clear CLASSPATH

If your CLASSPATH environment variable was set to a value that is not correct, or if your startup file or script is setting an incorrect path, then you can unset CLASSPATH with:

set CLASSPATH=

This command unsets CLASSPATH for the current command prompt window only. You should also delete or modify your startup settings to ensure that you have the correct CLASSPATH settings in future sessions.

Change Startup Settings

If the CLASSPATH variable is set at system startup, then the place to look for it depends on your operating system:

Windows 95 and 98: Examine autoexec.bat for the set command.

Other (Windows NT, Windows 2000, . ): The CLASSPATH environment variable can be set with the System utility in the Control Panel.

If the CLASSPATH variable is set at system startup, then the place to look for it depends on the shell you are running:

The csh , tcsh shells : Examine your .cshrc file for the setenv command.

The sh , ksh shells : Examine your .profile file for the export command.

Class Path Wild Cards

Class path entries can contain the base name wildcard character (*), which is considered equivalent to specifying a list of all of the files in the directory with the extension .jar or .JAR . For example, the class path entry mydir/* specifies all JAR files in the directory named mydir . A class path entry consisting of * expands to a list of all the jar files in the current directory. Files are considered regardless of whether they are hidden (have names beginning with ‘.’).

A class path entry that contains an asterisk (*) does not match class files. To match both classes and JAR files in a single directory mydir , use either mydir:mydir/* or mydir/*:mydir . The order chosen determines whether the classes and resources in mydir are loaded before JAR files in mydir or vice versa.

Subdirectories are not searched recursively. For example, mydir/* searches for JAR files only in mydir , not in mydir/subdir1 , mydir/subdir2 , and so on.

The order in which the JAR files in a directory are enumerated in the expanded class path is not specified and may vary from platform to platform and even from moment to moment on the same machine. A well-constructed application should not depend upon any particular order. If a specific order is required, then the JAR files can be enumerated explicitly in the class path.

Expansion of wild cards is done early, before the invocation of a program’s main method, rather than late, during the class-loading process. Each element of the input class path that contains a wildcard is replaced by the (possibly empty) sequence of elements generated by enumerating the JAR files in the named directory. For example, if the directory mydir contains a.jar, b.jar, and c.jar, then the class path mydir/* is expanded into mydir/a.jar:mydir/b.jar:mydir/c.jar , and that string would be the value of the system property java.class.path.

The CLASSPATH environment variable is not treated any differently from the -classpath or -cp options. Wild cards are honored in all of these cases. However, class path wild cards are not honored in the Class-Path jar-manifest header.

Class Path and Package Names

Java classes are organized into packages that are mapped to directories in the file system. But, unlike the file system, whenever you specify a package name, you specify the whole package name and never part of it. For example, the package name for java.awt.Button is always specified as java.awt .

For example, suppose you want the Java JRE to find a class named Cool.class in the package utility.myapp. If the path to that directory is C:\java\MyClasses\utility\myapp , then you would set the class path so that it contains C:\java\MyClasses . To run that application, you could use the following java command:

java -classpath C:\java\MyClasses utility.myapp.Cool

The entire package name is specified in the command. It is not possible, for example, to set the class path so it contains C:\java\MyClasses\ utility and use the command java myapp.Cool. The class would not be found.

You might wonder what defines the package name for a class. The answer is that the package name is part of the class and cannot be modified, except by recompiling the class.

An interesting consequence of the package specification mechanism is that files that are part of the same package can exist in different directories. The package name is the same for each class, but the path to each file might start from a different directory in the class path.

Folders and Archive Files

When classes are stored in a directory (folder), such as c:\java\MyClasses\utility\myapp , then the class path entry points to the directory that contains the first element of the package name (in this case, C:\java\MyClasses , because the package name is utility.myapp).

When classes are stored in an archive file (a zi p or JAR file) the class path entry is the path to and including the zip or JAR file. For example, the command to use a class library that is in a JAR file as follows:

java -classpath C:\java\MyClasses\myclasses.jar utility.myapp.Cool

Multiple Specifications

To find class files in the directory C:\java\MyClasses and classes in C:\java\OtherClasses , you would set the class path to the following. Note that the two paths are separated by a semicolon.

java -classpath C:\java\MyClasses;C:\java\OtherClasses .

Specification Order

The order in which you specify multiple class path entries is important. The Java interpreter will look for classes in the directories in the order they appear in the class path variable. In the previous example, the Java interpreter will first look for a needed class in the directory C:\java\MyClasses . Only when it does not find a class with the proper name in that directory will the interpreter look in the C:\java\OtherClasses directory.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *