Как импортировать библиотеку в java
Перейти к содержимому

Как импортировать библиотеку в java

  • автор:

Как с помощью maven подключить библиотеку к проекту

Спросите кого-нибудь, для чего вообще нужен Maven — 90 процентов поголовья программистов ответит, что именно для этого и будут во многом правы.

Если в случае с, например, C++ подключение библиотеки к своему проекту — это серьёзный шаг, который гарантированно усложнит сборку до такой степени, что придётся включить инструкции по подключению данной конкретной библиотеки в readme, то в случае с Java это делается легко и непринуждённо — не в последнюю очедь благодаря Maven.

Хочу отметить, что статья предназначена для тех, кто начал изучать java относительно недавно и хотя уже знает из предыдущей статьи, что такое maven — о том, что такое библиотеки, знает не очень хорошо, а как их подключать не знает вообще.

Как добавить в проект новый класс

Для того, чтобы использовать в своём коде какой-нибудь класс, помимо стандартного, нужно этот класс создать, то есть сделать соответствующий файл и написать внутри этого файла соответствующий код.

Свеженаписанный класс должен лежать там же, где и все остальные классы иначе компилятор его не увидит. Теперь, для того, чтобы его использовать, достаточно добавить в использующий его класс соответствующую директиву import.

Предлагаю присутствущим потратить минуту-другую на выражение благодарности капитану Очевидность, а после продолжить чтение.

Как добавить в проект класс, написанный кем-то другим

Ответ, вообще говоря, очевиден — надо скопировать этот класс в свой код.

Кроме того, что немножко менее очевидно, нужно скопировать в свой проект все классы, которые используются классом, ради которого всё затевалось.

Классы, используемые каким-то другим классом, кстати, принято называть зависимостями (dependencies), этого класса.

У такого подхода есть очевидный минус. Для каждого класса надо выискивать зависимости, а потом руками копировать их к себе. Если позже во всей этой куче кода найдётся какой-нибудь баг, то после появления фикса придётся повторить процесс заново.

Как добавить в проект класс, написанный кем-то другим, не копируя его в свой код

Во всех более-менее современных языках программирования эта проблема уже решена.

Всегда можно сказать компилятору, что классы нужно брать не только из директории с проектом, но и из других, указанных программистом директорий. В Java это делается с помощью параметра classpath.

Если вы работаете с Java то понимать, что такое classpath — строго обязательно, но конкретно для того, чтобы добавить к проекту библиотеку с помощью maven, этого знать не нужно. В контексте нашей темы можно считать classpath сущностью, в которой перечислены все места, где компилятор будет искать классы, необходимые приложению. Если какого-нибудь из этих классов нет ни в одном из этих мест, то программа работать не будет.

Теперь для того, чтобы использовать чужой класс, достаточно скачать код с этим классом, и добавить в classpath директорию, в которую скачан этот код.

По сравнению с предыдущим способом это заметный прогресс. Теперь нет никакой необходимости вручную отслеживать все зависимости того единственного класса, который нужен для работы вашего приложения. Для добавки багфиксов и всего такого достаточно просто скачать новую версию кода.

Вот собственно мы и подошли к ответу на вопрос, что такое библиотека.

Что такое библиотека

Библиотекой принято называть тот самый код, корневую директорию которого нужно добавить в classpath. То есть совокупность нужного нам класса и его зависимостей, а также классов, которые не являются зависимостями нужного нам класса, но содержатся в коде.

В случае с Java, код, который мы добавляем в classpath, можно скомпилировать и добавить в classpath уже директорию со скомпилированным кодом.

Ещё можно заархивировать скомпилированный код в формате zip, поменять расширение файла с архивом на jar и добавить в classpath файл уже этот файл. В контексте разработки на Java, jar файл тоже называется библиотекой.

jar файлы не решают ни одной из изложенных выше проблем, но их использование существенно облегчает передачу библиотек между программистами.

Но, есть одна существенная проблема, которую jar файлы тоже никак решить не помогают.

Классы, которые использует библиотека, могут содержаться не в ней, а в какой-нибудь другой библиотеке, которая по аналогии с предыдущим случаем, тоже называется зависимостью.

Как добавить в проект библиотеку, использующую другую библиотеку

Для того, чтобы добавить в проект библиотеку со всеми её зависимостями, придётся эти зависимости скачать и по одной добавить в проект. При обновлении каждой библиотеки зависимости придётся качать заново.

Может случиться так, что при обновлении какой-нибудь зависимости библиотека, класс из которой мы собираемся использовать в своём проекте, перестанет работать корректно — нам придётся внимательно следить за тем, чтобы такого не случилось и ответственно подходить к каждому обновлению, а лучше, обновлять библиотеки только если без обновления нельзя обойтись вообще.

Как убедиться, что обновление зависимости ничего не сломает

Сторого говоря — никак.

Необходимо, конечно, обновить зависимость и запустить юнит тесты. Если они не проходят, то определённо можно сказать, что что-то сломалось.

Если нет, то это является слабым свидетельством, что поломка отсутствует, но ничего не доказывает.

Но положим, что юнит тестам можно доверять. В этом случае при добавлении библиотеки придётся вручную проверить её совместимость с зависимостями запустив прилагаемые юнит тесты и делать это при каждом обновлении. Это, поверьте, мне тяжело.

Для того, чтобы избежать этой нудной и сложной работы, между программистами всего мира существует негласная договорённость. Библиотеки принято версионировать.

При создании библиотеки программист пишет её код, убеждается, что он работает корректно, а потом присваивает этому коду идентификатор, например номер, и после этого делает код доступным для других программистов чтобы они могли использовать эту библиотеку в своём коде.

Если другие программисты находят в библиотеке ошибку, то создатель библиотеки не просто молча её исправляет, а после исправления изменяет идентификатор библиотеки и теперь миру доступно две библиотеки с одинаковым названием, но разными идентификаторами.

Этот идентификатор принято называть версией библиотеки.

Версию библиотеки программист обновляет не только при исправлении ошибок, но и вообще при любом изменении.

Программисты, использующие эту стороннюю библиотеку при создании своих библиотек, или просто программ, указывают в документации не только название, но и версию, с которой их библиотека гарантировано работает корректно.

То есть работу по проверке того, какие версии зависимостей нужно использовать, берёт на себя один человек, остальные просто пользуются плодами его трудов.

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

При обновлении какой-нибудь из библиотек процесс надо повторить. Это, поверьте мне, мучительно.

Как получить список всех библиотек, нужных проекту и добавить их в проект автоматически

И тут на помощь приходит Maven. Он формализует негласную договорённость между программистами и делает её гласной.

Если для каждой библиотеки есть список зависимостей, с чётко определёнными версиями, то составить список всех нужных проекту библиотек сложности не составляет.

Скопировать эти библиотеки на машину программиста и добавить их в classpath — тоже не высшая математика. Нужно только знать, откуда качать библиотеки и описания их зависимостей, а также в каком формате эти зависимости описаны.

Эти вопросы в Maven успешно решены.

Как подключить библиотеку к Maven проекту

Тут всё в общем-то банально. Библиотека в понимании Maven, является артефактом, нужным для сборки программы.

У каждого артефакта, как мы помним, есть groupId, artifactId и version. Нужно только указать maven, что данный артефакт является зависимостью проекта.

Список зависимостей должен быть обернут тегом dependencies. Каждая отдельная зависимость должна быть обёрнута тегом dependency. Внутри тега dependency в тегах groupId, artifactId и version нужно указать значения соответствующих параметров.

Тут наверное надо дать пример pom.xml с добавленной библиотекой. Вот пример:

Тут мы подключили к проекту библиотеку, с кучей статических методов, выполняющих стандартные задачи. Одной из таких задач является расширение массива и добавление в него дополнительного элемента.

Вот например так:

Чтобы скомпилировать код надо написать

Этот код выведет Hello world, но, в отличии от предыдущей статьи, уже новым прогрессивным методом. С помощью библиотеки.

Вот собственно и всё.

Зависимости подключённого к проекту артефакта maven найдёт сам, сам составит список всех библиотек, необходимых проекту, включая зависимости зависимостей и зависимости зависимостей зависимостей, сам скачает их на машину, на которой происходит сборка и сам добавит их в classpath.

How to include libraries in Java without using an IDE

How do I import libraries in my Java program without using an IDE, like NetBeans?

In NetBeans I do it this way:

Enter image description here

How can I achieve the same thing by just using Notepad++ or Programmer’s Notepad. As much as possible I don’t want to use NetBeans because it would be overkill since I’m only working on simple projects.

Peter Mortensen's user avatar

6 Answers 6

If your main class is in a package,

then you’ll need

Peter Mortensen's user avatar

In addition to Bala R’s post, adding multiple files and locations is perfectly OK too.

-cp and -classpath are the same thing.

If you’re on Solaris (and some other Unix flavors), change the ‘ ; ‘ to ‘ : ‘.

Peter Mortensen's user avatar

All of the other posters are spot on; you just need to add the JAR file to your classpath.

Java offers many mechanisms for setting the classpath, including via the command line, via an environment variable, and through setting it in the MANIFEST.MF of an executable Java JAR file.

These are all a pain in the neck to manage. It’s good to know the technique, and understand the basics. But it’s really a bad idea to actually use them.

You should do this.

First, put all of your Java libraries in a single place on your system. C:\java\libraries, or whatever. Someplace that you remember, and someplace accessible by all of your projects.

Next, name all of your libraries using their version numbers. If you using Log4j v1.4.1, then put the JAR file in a log4j-1.4.1 directory in your library area. This gives you "free" library versioning.

Finally, learn Ant. For simple projects, Ant is simple. Use the Ant build.xml file to compile, test, and run your application.

Why? Several reasons.

Because once it’s set up, adding a new library to your project is trivial; you add a line to your build.xml file. Ant lets you more easily handle simple abstractions (like where all of your libraries are located).

The build.xml file is self-contained. If you use, say, an environment variable for the classpath, then the classpath for one project may be different from that of another. That means resetting the environment variable. Continue this and you’ll end up swearing at some "new problem" where it "worked before" when it’s because you had your classpath set wrong. Set it once in the build.xml file, and forget it.

Ant is portable. It runs the same on Windows, on Linux, on Mac, on AS/400, it runs everywhere that Java runs, unlike shells scripts or BAT files.

It’s lightweight. Simple Ant scripts are simple. They don’t bring a lot of baggage with them, and you can always make them scary complicated. It’s much simpler than Maven for just builds.

Most IDEs support Ant directly. If you decided to go back to an IDE, most can simply use your Ant build file with minimal configuration.

This is how you solve your classpath problem with Notepad++. Setting the classpath works, but it doesn’t go far enough. It’s a pain to administer and manage. Learning the basics of Ant will take you much farther with minimal work.

Как импортировать библиотеку в java

Java Library is the collection of classes that are written by some other programmers that we can use in our code by downloading those classes. Java library allows you to read and modify bytecode generated by an application. Some of the popular bytecode libraries in the Java world are “javassist” and “Cglib Nodep.” Eclipse is an open-source community rather than the best open source IDE whose projects are focused on building an extensible development platform, runtimes, and application frameworks for building, deploying and managing software across the entire software lifecycle.

Note: Here most users do tend to forget to set a path after installing libraries, so we will be covering it in two halves where we will be covering

  • Installation of java libraries in first half
  • Configuring build path

A. INSTALLATION OF JAVA LIBRARIES

Follow are the sequential steps to be followed in order to install java libraries.

Step 1: Download and extract the library from its website

Step 2: You need to locate the jar file(s) for the library and where the API documentation is stored. Once you know where the files are located, you can add a user library to Eclipse.

Step 3: Open the “Preferences” window in Eclipse. Navigate to “Java » Build Path » User Libraries” then on the left-hand side click on the “New” button, enter the file name and then click on the OK button.

Step 4: After that, you need to click the “Add External JARs” button to add the jar file. Browse the jar file(s) required for the library and click the “Open” button.

Step 5: Go and select the “Javadoc location” entry and click the “Edit” button.

Step 6: Browse to the folder or directory containing the API documentation and click the “Validate” button.

Step 7: Click “OK” until you exit the “Preferences” window entirely.

Note: Once you have successfully added the user library, you need to add the user library to your project’s build path.

B. CONFIGURING BUILD PATH

Step 1: Right-click the project and select “Build Path » Add Libraries…”.

Step 2: Dialog the window that pops up, select “User Library” and click the “Next” button.

Step 3: Select the user libraries you want to add and click “Finish”.

Now you can see the library listed in your project directory underneath the default Java class files.

Note: You need to do this for every project that needs this library.

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.

Add

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 the module or modules to which you want to add the new library.

Add

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 .

the Add button

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 .

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

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