- Libraries
- Define a library
- Define a global library
- Define a project library
- Add a library to module dependencies
- Download a library from Maven
- Add classes to a library
- Include specific transitive dependencies
- Change the library level
- Move a library to a higher level
- Copy a library to a lower level
- Exclude library items
- Exclude items from a project or a global library
- Exclude items from a module library
- Configure a custom remote repository
- Configure library documentation
- Specify library documentation paths
- Add library documentation to your project
- Подключение библиотек в Java
- Подключение Джава-библиотек в Eclipse
- Подключение библиотек Java в Maven и Apache-Ant
- Как подключить Java-библиотеку вручную
- Подключение jar-библиотек в Java
Libraries
A library is a collection of compiled code that you can add to your project. In IntelliJ IDEA, libraries can be defined at three levels: global (available for many projects), project (available for all modules within a project), and module (available for one module).
A Java library can include class files, archives and directories with class files as well as directories with native libraries .dll , .so , or .jnilib .
This information is valid for projects that are built with the native IntelliJ IDEA builder. If you’re using a build tool, such as Maven or Gradle, make all changes using the build file.
Define a library
After you define a library and add it to module dependencies, the IDE will be supplying its contents to you as you write your code. IntelliJ IDEA will also use the code from the libraries to build and deploy your application.
You can also create a new library from the JAR files located within a project content root. Select these files in the Project tool window, and then select Add as Library from the context menu.
Define a global library
- From the main menu, select File | Project Structure Ctrl+Alt+Shift+S .
- Under Platform Settings , select Global Libraries .
- Click and select one of the following:
- Select Java or Kotlin/JS to add a library from the files located on your computer.
- Select From Maven to download a library from Maven.
In this dialog, you can also: add classes to an existing library, specify an external documentation URL, exclude items from a library, or remove a library.
References to global libraries are stored in the IDE configuration directory in options | applicationLibraries.xml .
Define a project library
- From the main menu, select File | Project Structure Ctrl+Alt+Shift+S .
- Under Project Settings , select Libraries .
- Click and select one of the following:
- Select Java or Kotlin/JS to add a library from the files located on your computer.
- Select From Maven to download a library from Maven.
- Select the module or modules to which you want to add the new library.
In this dialog, you can also: add classes to an existing library, specify an external documentation URL, exclude items from a library, or remove a library.
References to project libraries are stored together with the project in the .idea folder in libraries .
Add a library to module dependencies
Global and project libraries are not available until you add them to module dependencies.
- From the main menu, select File | Project Structure | Project Settings | Modules .
- Select the module for which you want to add a library and click Dependencies .
- Click the button and select Library .
- In the dialog that opens, select a project or a global library that you want to add to the module. Alternatively, click New Library and select how do you want to add a new library: you can add a Java and Kotlin libraries from files on your computer, or download a library from Maven.
References to module libraries are stored in the module .iml file. This file is used for keeping module configuration. For more information on module files, refer to Modules.
Download a library from Maven
- From the main menu, select File | Project Structure Ctrl+Alt+Shift+S and click Libraries .
- Click and select From Maven .
- In the next dialog, specify the library artifact (for example, org.jetbrains:annotations:16.0.2 ). If you don’t know its exact name, enter the key words and click . You can also specify another library location, and select whether you want to download transitive dependencies, source files, Javadoc files, or annotations.
IntelliJ IDEA will download the library from Maven or Nexus public repositories. You can also configure a custom remote repository.
Add classes to a library
Once the library is added, you can add more classes to it:
- From the main menu, select File | Project Structure . Then click Global Libraries to modify a global library or Libraries to modify a project library. To modify a module library, select File | Project Structure from the main menu and go to Modules | Dependencies . Select the library that you want to modify and click .
- Click and select the classes you want to add in the dialog that opens. For a Java library, these may be individual class and java files, directories and archives jar and zip containing such files,or directories with Java native libraries .dll , .so or .jnilib .
- IntelliJ IDEA will analyze the selected files and folders, and automatically assign their contents to the appropriate library categories (Classes, Sources, Documentation, Native Library Locations, and so on). When IntelliJ IDEA cannot guess the category (for example, when you select an empty folder), a dialog will be shown, in which you will be able to specify the category yourself.
Include specific transitive dependencies
If you want to include only specific transitive dependencies, you can use the library properties editor.
- From the main menu, select File | Project Structure Ctrl+Alt+Shift+S , and go to Modules | Dependencies .
- Select the necessary Maven library and click .
- In the next dialog, click Edit , and then click Configure next to the Include transitive dependencies option.
- Select the dependencies you want to include in the library and click OK .
Change the library level
Move a library to a higher level
In IntelliJ IDEA, you can move a project or a module library to a higher level. This is helpful if you want to extend its scope of usage. For example, use this procedure if you want to use a module library across the project or the entire IDE.
- From the main menu, select File | Project Structure Ctrl+Alt+Shift+S and locate the library that you want to change.
- Right-click the necessary library and select Move to Project Libraries or Move to Global Libraries .
Copy a library to a lower level
You can create a copy of a library on a lower level. For example, use this procedure if you want to add more classes to a project library, but you want to use them in one module only.
- From the main menu, select File | Project Structure Ctrl+Alt+Shift+S and locate the library that you want to change.
- Right-click the necessary library and select Copy to Project Libraries or Add to Modules .
Exclude library items
IntelliJ IDEA allows you to temporarily exclude library items in order to increase IDE performance. You can exclude folders, archives (for example, JARs) and folders within archives.
Classes from excluded packages won’t be shown in code completion suggestion lists, references to such classes will be shown in the editor as unresolved, and so on. However, when you compile or run your code, a library will still be used as a whole, irrespective of whether there are excluded items in that library or not.
Exclude items from a project or a global library
- From the main menu, select File | Project Structure Ctrl+Alt+Shift+S and click Libraries .
- Click and select the library items that you want to exclude.
Exclude items from a module library
- From the main menu, select File | Project Structure Ctrl+Alt+Shift+S and go to Modules | Dependencies .
- Select the library that you want to modify and click .
- Click and select the library items that you want to exclude.
Excluded items will be marked with the icon. To return library items to their original state, remove the excluded items.
Configure a custom remote repository
You can view the full list of remote repositories and add a custom repository in the settings. Note that IntelliJ IDEA can load libraries from Maven even if you don’t use Maven as a build tool for your project.
- In the Settings dialog Ctrl+Alt+S , go to Build, Execution, Deployment | Remote Jar Repositories .
- Click Add in the corresponding dialog section, and specify the repository URL.
Configure library documentation
You can add library documentation to IntelliJ IDEA so that you can get information about symbols and method signatures right from the editor in the Quick Documentation popup.
You can also configure external documentation by specifying the path to the reference information online. External documentation opens the necessary information in a browser so that you can navigate to related symbols and keep the information for further reference at the same time.
If you’re downloading a library from Maven, select the JavaDoc checkbox to get the library documentation together with the library code.
Specify library documentation paths
To view external library documentation, configure the documentation URL first.
- In the Project Structure dialog Ctrl+Alt+Shift+S , select Libraries .
- Select the necessary library, click the icon and enter the external documentation URL.
- Apply the changes and close the dialog.
Add library documentation to your project
You can add downloaded documentation to your project to be able to access it offline.
- From the main menu, select File | Project Structure Ctrl+Alt+Shift+S and click Libraries .
- Select the library for which you want to add the documentation and click in the right section of the dialog.
- In the dialog that opens, select the file with the documentation and click Open .
- Apply the changes and close the dialog.
When the documentation is configured, you can open it in the editor.
Подключение библиотек в Java
Библиотека — готовый набор классов и компонентов, который встраивают в программу, чтобы реализовать некий функционал. Например, в тысячах казуальных игр музыку можно проигрывать одним и тем же способом. Чтобы не тратить время на работу со звуком, программисту достаточно подключить подходящую библиотеку.
Подключение Джава-библиотек в Eclipse
Если вы пользуетесь средой разработки Eclipse, подключение библиотек в Java займёт у вас меньше минуты:
- Разворачиваем дерево проекта в Package Explorer и находим папку libs. Если её нет — создаем.
- Кладем нужный .jar в libs.
- В появившемся окне выбираем «копирование файлов» (copy files) и жмём OK.
- Обновляем проект: правый клик — «Refresh».
Классы подключены и готовы к вызову из нашей программы.
Подключение библиотек Java в Maven и Apache-Ant
Минус подключения библиотек через IDE в том, что для пересборки проекта на другой машине нужна та же среда. Чтобы не зависеть от среды, используют системы сборки Maven и Ant.
Чтобы «прикрутить» библиотеку к проекту Maven, нужно указать её среди зависимостей в файле pom.xml. С библиотекой может подтянуться еще несколько зависимостей, которые подключаются к этой библиотеке. В случае с jar этого не происходит.
Как будет выглядеть наш pom.xml:
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 ru.team.project test-app 1.0 dependency> Допустим, нам нужна Javassist для редактирования байткода. ----> org.javassist javassist 3.21.0-GA
Теперь при компиляции проекта библиотека войдет в конечный .jar-файл.
В Ant принцип схожий, но редактировать нужно файл build.xml. Путь к подключаемым библиотекам пишут с помощью тегов и . Сначала объясняем, где искать библиотеку:
И далее передаём этот адрес тегу :
Как подключить Java-библиотеку вручную
Ваша IDE умеет подключать библиотеки, но как она это делает? Давайте посмотрим, что происходит на уровне файлов. Если библиотека написана на Джаве, её компоненты хранятся либо в архиве .jar, либо в исходниках .java. Более сложный вариант с интеграцией библиотек на C++ пока рассматривать не будем.
Подключение jar-библиотек в Java
Если на компьютере только одна версия Джавы — всё просто. Чтобы подключить .jar, достаточно положить его в папку lib директории Java на жестком диске. Виртуальная машина при ближайшем запуске сама возьмет код из библиотеки.
Когда вы используете одновременно несколько версий Java-машины, раскладывать файлы библиотек для каждой из них утомительно. Лучше указать путь к нужным классам с помощью ключа -classpath.
Открываем терминал и пишем:
java -classpath ./classes ru.аuthor.libname.Main
ru.аuthor.libname.Main — наша библиотека
Точкой перед «/» отмечают текущую директорию.
Можно перечислить несколько библиотек, код из которых компилятор соберет в порядке их перечисления:
java -classpath ./classes;./lib/l1-0.1.jar;./lib/l2-1.5.jar ru. аuthor.libname.Main
Теперь вы умеете подключать библиотеки даже в нестандартной ситуации: когда не установлена IDE или нужно скорректировать очередность подключения.