Classpath java как прописать

от admin

# The Classpath

Note that the -classpath (or -cp ) option takes precedence over the CLASSPATH environment variable.

Note that this only applies when the JAR file is executed like this:

In this mode of execution, the -classpath option and the CLASSPATH environment variable will be ignored, even if the JAR file has no Class-Path element.

If no classpath is specified, then the default classpath is the selected JAR file when using java -jar , or the current directory otherwise.

# Adding all JARs in a directory to the classpath

If you want to add all the JARs in directory to the classpath, you can do this concisely using classpath wildcard syntax; for example:

This tells the JVM to add all JAR and ZIP files in the someFolder directory to the classpath. This syntax can be used in a -cp argument, a CLASSPATH environment variable, or a Class-Path attribute in an executable JAR file’s manifest file.See Setting the Class Path: Class Path Wild Cards

(opens new window) for examples and caveats.

  1. Classpath wildcards were first introduced in Java 6. Earlier versions of Java do not treat "*" as a wildcard.
  2. You cannot put other characters before or after the ""; e.g. "someFolder/.jar" is not a wildcard.
  3. A wildcard matches only files with the suffix ".jar" or ".JAR". ZIP files are ignored, as are JAR files with a different suffixes.
  4. A wildcard matches only JAR files in the directory itself, not in its subdirectories.
  5. When a group of JAR files is matched by a wildcard entry, their relative order on the classpath is not specified.

# Load a resource from the classpath

It can be useful to load a resource (image, text file, properties, KeyStore, . ) that is packaged inside a JAR. For this purpose, we can use the Class and ClassLoader s.

Suppose we have the following project structure :

And we want to access the contents of file.txt from the Test class. We can do so by asking the classloader :

By using the classloader, we need to specify the fully qualified path of our resource (each package).

Or alternatively, we can ask the Test class object directly

Using the class object, the path is relative to the class itself. Our Test.class being in the com.project package, the same as file.txt , we do not need to specify any path at all.

We can, however, use absolute paths from the class object, like so :

# Classpath path syntax

The classpath is a sequence of entries which are directory pathnames, JAR or ZIP file pathnames, or JAR / ZIP wildcard specifications.

Sometimes it is necessary to embed a space in a classpath entry

(The details may depend on the command shell that you use.)

# Dynamic Classpath

Sometimes, just adding all the JARs from a folder isn’t enough, for example when you have native code and need to select a subset of JARs. In this case, you need two main() methods. The first one builds a classloader and then uses this classloader to call the second main() .

Here is an example which selects the correct SWT native JAR for your platform, adds all your application’s JARs and then invokes the real main() method: Create cross platform Java SWT Application

# Mapping classnames to pathnames

The standard Java toolchain (and 3rd-party tools designed to interoperate with them) have specific rules for mapping the names of classes to the pathnames of files and other resources that represent them.

The mappings are as follows

  • For classes in the default package, the pathnames are simple filenames.
  • For classes in a named package, the package name components map to directories.
  • For named nested and inner classes, the filename component is formed by joining the class names with a $ character.
  • For anonymous inner classes, numbers are used in place of names.

This is illustrated in the following table:

Classname Source pathname Classfile pathname
SomeClass SomeClass.java SomeClass.class
com.example.SomeClass com/example/SomeClass.java com/example/SomeClass.class
SomeClass.Inner (in SomeClass.java ) SomeClass$Inner.class
SomeClass anon inner classes (in SomeClass.java ) SomeClass$1.class , SomeClass$2.class , etc

# What the classpath means: how searches work

The purpose of the classpath is to tell a JVM where to find classes and other resources. The meaning of the classpath and the search process are intertwined.

The classpath is a form of search path which specifies a sequence of locations to look for resources. In a standard classpath, these places are either, a directory in the host file system, a JAR file or a ZIP file. In each cases, the location is the root of a namespace that will be searched.

The standard procedure for searching for a class on the classpath is as follows:

  • If the entry is a filesystem directory:
      1. Resolve `RP` relative to `E` to give an absolute pathname `AP`. 1. Test if `AP` is a path for an existing file. 1. If yes, load the class from that file
      1. Lookup `RP` in the JAR / ZIP file index. 1. If the corresponding JAR / ZIP file entry exists, load the class from that entry.
    • Lookup RP in the JAR / ZIP file index.
    • If the corresponding JAR / ZIP file entry exists, load the class from that entry.

    The procedure for searching for a resource on the classpath depends on whether the resource path is absolute or relative. For an absolute resource path, the procedure is as above. For a relative resource path resolved using Class.getResource or Class.getResourceAsStream , the path for the classes package is prepended prior to searching.

    (Note these are the procedures implemented by the standard Java classloaders. A custom classloader might perform the search differently.)

    # The bootstrap classpath

    The normal Java classloaders look for classes first in the bootstrap classpath, before checking for extensions and the application classpath. By default, the bootstrap classpath consists of the "rt.jar" file and some other important JAR files that are supplied by the JRE installation. These provide all of the classes in the standard Java SE class library, along with various "internal" implementation classes.

    Under normal circumstances, you don’t need to concern yourself with this. By default, commands like java , javac and so on will use the appropriate versions of the runtime libraries.

    Very occasionally, it is necessary to override the normal behavior of the Java runtime by using an alternative version of a class in the standard libraries. For example, you might encounter a "show stopper" bug in the runtime libraries that you cannot work around by normal means. In such a situation, it is possible to create a JAR file containing the altered class and then add it to the bootstrap classpath which launching the JVM.

    The java command provides the following -X options for modifying the bootstrap classpath:

    • -Xbootclasspath:<path> replaces the current boot classpath with the path provided.
    • -Xbootclasspath/a:<path> appends the provided path to the current boot classpath.
    • -Xbootclasspath/p:<path> prepends the provided path to the current boot classpath.

    Note that when use the bootclasspath options to replace or override a Java class (etcetera), you are technically modifying Java. There may be licensing implications if you then distribute your code. (Refer to the terms and conditions of the Java Binary License . and consult a lawyer.)

    # Remarks

    Java class loading

    The JVM (Java Virtual Machine) will load classes as and when the classes are required (this is called lazy-loading). Locations of the classes to be used are specified in three places:-

    1. Those required by the Java Platform are loaded first, such as those in the Java Class Library and it’s dependencies.
    2. Extension classes are loaded next (i.e. those in jre/lib/ext/ )
    3. User-defined classes via the classpath are then loaded

    Classes are loaded using classes that are subtypes of java.lang.ClassLoader . This described in a more detail in this Topic: Classloaders

    Classpath

    The classpath is a parameter used by the JVM or compiler which specifies the locations of user-defined classes and packages. This can be set in the command line as with most of these examples or through an environmental variable ( CLASSPATH )

    Back to the basics of Java — Part 1: Classpath

    My favourite programming language has always been Java, coincidentally it was also my first language I ever used. If you’re like me, or just wants to learn more about the awesome language & technology that is Java, then this two part series is for you.

    In these short series, you will learn about the following.

    • Part 1: Classpath
    • Part 2: The JAR

    So, why did I decide to write these articles? Well, there was some aspects of Java I did not fully comprehend (such as the classpath) and I realized the reason for this is because I have been using an IDE and build tools.

    The issue with an IDE is that it hides a lot of stuff which hinders a fully comprehensive understanding. In other words, I thought it was time to get a little bit more comfortable with the java cli tools and going back to basics.

    Now let’s get down to it. In this part I will explain what the classpath is and how to use it correctly (and incorrectly).

    Classpath

    The classpath is simply a list of directories, JAR files, and ZIP archives to search for class files [1]. The runtime needs to know where to find your compiled classes so that’s what you’re providing here.

    There are some things that you should be aware of though regarding how you specify the paths. To explain this I will create a dummy project, see below for the structure.

    And here are the source files just so you know what we are dealing with.

    Main.java

    Util.java

    I will be using this structure for the following parts as well so If you want to follow along I suggest you create it as well before proceeding.

    A short note on packages.

    If you are new to java it can be helpful to know that packages are generally suppose to be mirrored by the file structure. Take the Utils.java file for instance, it has the package myprogram.utils because it is in that folder.

    The structure as provided is not really required by the compiler. However, it is required by the java command to run.

    Let’s compile this little project.

    First we create a bin folder to hold the compiled stuff in the root project folder then compile the two files [2].

    You should now have the following file structure.

    If we now move to the bin folder we can run the main class.

    Great, so why does this work? Because the default value for the classpath is the current directory. It needs to find two class files; Main.class and Utils.class, how and where does it look? Given the current class path of bin and our main class myprogram.Main it will look in this directory to try and find the following:

    • myprogram/Main.class
    • myprogram/utils/Util.class

    Which we know exists, so the program runs successfully.

    Now let’s change it up a little bit. Let’s add a new folder lib on the same level as bin and move the Utils.class so that it now looks like this.

    Error 1— No classpath specified

    If we now move to the bin folder and try and run the same command we will get an error because it cant find the Util.class file.

    Error 2 — Adding a class file to the classpath

    We will try and solve this by adding the class file to the classpath (we are running all these commands from the bin folder).

    Ouch, now it cannot find the Main.class file? Because as previously explained, it will try and find the files in the specified directories provided in the classpath. And we did not provide a directory. So let’s do that instead.

    Error 3 — Adding one directory to the classpath

    Okay, same error. What happened here? Since we provided a classpath argument that overrides the default one (which is the current directory) it cannot find our Main.class file anywhere. Let’s add that. On Unix systems you separate with a colon (:) and on Windows, you use a semi-colon (;).

    Error 4 — Adding more paths to the classpath

    Okey, now it seems that it can find the Main.class file. But it still cannot find the Util.class file. As previously explained it will try and find the following files using any of the classpaths.

    • myprogram/Main.class
    • myprogram/utils/Util.class

    In this case we have two classpaths.

    • ../lib/myprogram/utils/
    • .

    So simply put, it will try and append the classpaths to the required files to see if they exist, I image the process would look something like this.

    Final solution

    Can we solve this by adding those subfolders under lib? Sure we can, which will work. However, instead of adding those folders let’s modify the classpath argument instead so that it looks like this.

    This works because it will now be able to find Utils.class file using the first path.

    I hope that some of the errors here have helped your understanding of the class path. It seems that a lot of tutorials only present the correct way of doing things but I find that seeing the incorrect way of doing things helps my learning a lot more.

    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

    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 <jdk-dir>/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 <jdk-dir>/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:

    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:

    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:

    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:

    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.

    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.

    What is a classpath and how do I set it?

    Please explain what was meant by classpath in this context, and how I should set the classpath.

    10 Answers 10

    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:

    Or sometimes you ‘bulk import’ stuff by saying:

    So later in your program when you say:

    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:

    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:

    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).

    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.

    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 ,

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

    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:

    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:

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

    .\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:

    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.

    Читать:
    Как проверить счетчик воды кофемашины krups

Похожие статьи