- how can i use referenced libraries
- 1 Answer 1
- JRE & JDK: Java Class Library (JCL)
- Package outline
- Key packages
- java.awt : Abstract Window Toolkit
- java.io : Basic input/output
- java.lang : Core object types
- java.net : Basic network addressing & access
- java.math : Arbitrary-precision numeric types & operations
- java.nio.file : Filesystem operations
- java.util : Utility classes and interfaces
- Что такое библиотеки классов Java?
how can i use referenced libraries
Hi I made one jar file with 3 classes.They work fine they are supporting file for getting HXM data.Now when i made jar i want to use it in my next project.I imported it and now it is in referenced libraries.But i can not find how can i use the libraries. in old project from i take the 3 .class file they have the paths: sk.csabi.hxm.* but now how can i import and use them? thanks
1 Answer 1
Your question isn’t very clear but it seems like you’re asking how to add the JAR to your project classpath in Eclipse.
What you’re looking to do is add the libraries to your project’s build path (the class path that will be used while compiling). In Eclipse, you can do this by right-clicking your project and choosing Properties (or hitting [Alt]+[Enter] when the project is selected in Project Explorer , Navigator or Package Explorer views) and then Java Build Path from the sidebar and the Libraries tab where you can add JARs.
Note the difference between Add JARs and External JARs is that External JARs will add an external dependency in your project since the absolute path to the JAR on your filesystem will be put into your project’s configuration. With Add JARs you can select JARs from within your workspace.
I find it to be a good practice to create a lib folder (at the same level as my src folder) and put all my JARs in there and then add them to the build path with the Add JARs option. This makes the project portable since there are only relative paths referring to resources within the project rather than absolute paths or resources from other workspace projects.
JRE & JDK: Java Class Library (JCL)
The Java Class Library ( JCL ), often referred to as the Java standard library, contains thousands of classes and interfaces, written almost entirely in Java, 1 providing a wide range of capabilities. No Java application or library (not even a single Java class) can be written without reference (whether explicit or implicit, direct or indirect) to at least one class in this library. On the other hand, many non-trivial Java applications and libraries make use of no other libraries beyond the JCL .
Package outline
This outline, and the selected descriptions below, are not intended to give a complete picture of the JCL , but only to summarize its most commonly used packages.
- Java Development Kit ( JDK )
- Development tools
- Java Runtime Environment ( JRE )
- Runtime tools
- Java Class Library ( JCL )
- java : Root package for library core
- java.awt : Abstract Window Toolkit
- java.io : Basic input/output
- java.lang : Core object types
- java.net : Basic network addressing & access
- java.math : Arbitrary-precision numeric types & operations
- java.nio : High-level extensions to input/output features
- java.nio.file : Filesystem operations
- …
- java.util.concurrent : High-level concurrency
- java.util.function : Core functional interfaces
- java.util.jar : Operations on JAR (Java Archive) files
- java.util.prefs : Preferences & configuration settings managements
- java.util.regex : Regular expressions
- java.util.stream : Functional operations on streams of values
- java.util.zip : Operations on ZIP and GZIP files
- …
- javax.crypto : Cryptographic operations
- javax.script : Scripting language support
- javax.sql : Enterprise RDBMS access
- javax.swing : Swing GUI library
- javax.xml : XML processing
- …
Key packages
java.awt : Abstract Window Toolkit
The Abstract Window Toolkit ( AWT ) was the first GUI toolkit available for Java. It’s considered a “heavyweight” GUI toolkit, since all of the elements are implemented directly in terms of the corresponding elements in the underlying operating system, rather than taking advantage of Java capabilities for memory, display, and control management.
Currently, almost none of the GUI code we write uses AWT elements directly. In particular, we don’t use AWT in Android programming: the only elements of AWT that are included in the Android standard library are the NumericShaper , NumericShaper.Range , and TextAttribute classes, used primarily in computing font metrics. On the other hand, even indirect dependencies can complicate things: some 3 rd -party Java libraries we’d like to use have AWT dependencies, so our code would depend on AWT indirectly—which would (for example) make it impossible for us to use such a library in an Android app.
java.io : Basic input/output
This contains interfaces and classes for reading/writing data from/to byte-level streams associated with files, network connections, and memory buffers; reading and writing char and higher-level primitive and class values; reading and writing file metadata (name, size, permissions, and other attributes); creating and deleting files and directories.
java.lang : Core object types
The interfaces and classes in this package provide a significant portion of the runtime infrastructure for even the most basic Java applications. For example, every class extends (directly or indirectly) the java.lang.Object class, and every Java application includes a main method that takes an array of java.lang.String references as a parameter. Those 2 classes—and several others in this package—play key roles in the Java language itself, and are given special treatment by the Java compiler.
This is the only package that is automatically imported by javac (the Java compiler). However, this automatic import is only for the java.lang package itself, and not any subpackages (e.g. java.lang.reflect ).
java.net : Basic network addressing & access
This package includes low-level (e.g. IP addresses and sockets) and high-level (e.g. connections, URLs, and URIs) classes and interfaces for network operations.
java.math : Arbitrary-precision numeric types & operations
Beyond the numeric primitive types ( byte , char , short , int , long , float , double ) and the corresponding wrapper classes ( Byte , Short , Integer , Long , Float , Double ) 2 , there are 2 classes in the java.math package of the standard library that support integer values of arbitrary size, floating-point values of arbitrary precision, and operations on those values: BigInteger and BigDecimal . There are theoretical limits on the size and precision of values of these types—but for most practical purposes, the operative constraint is system memory.
Note that the Math class, which defines a wide range of methods for performing calculations on the primitive numeric types, is not part of the java.math package; instead, it is in java.lang .
java.nio.file : Filesystem operations
This package extends the features of java.io to provide high-level access to directory and file contents. This package was introduced in Java 1.7, and extended significantly to support the streams framework introduced in Java 1.8.
java.util : Utility classes and interfaces
This package contains the classes and interfaces of the Java Collections Framework, defining an extensive set of collections (lists, sets, and maps), and implementing key algorithms that operate on those collections. In addition, this package contains classes for managing dates, times, and calendars; basic text formatters and input tokenizers; classes providing utility operations on arrays and other objects; timers; null-aware container classes; etc.
(As seen from the abbreviated list above, the subpackages of this package are similarly extensive and varied.)
- Some portions of the JCL involve platform-specific use of OS services: graphics display, networking, filesystem, etc. These low-level integrations are typically written in C, and integrate with the JCL via the Java Native Interface ( JNI ). ↩
- There is a Character wrapper type, corresponding to the char primitive type; however, Character is not a subclass of Number , so it is not considered a numeric object type. ↩
Что такое библиотеки классов Java?
В этой статье мы очень обзорно познакомимся с такими понятиями:
В обычной жизни, если Вы пойдёте в библиотеку или книжный магазин, естественно, Вы там увидите огромное количество книг, которые отвечают на самые разные вопросы: по истории, математике, химии, социлогии и т.д. И не надо всё выдумывать с нуля — взял книгу и получил ответы/решения на многие вопросы.
Причём все книги разложены строго по полочкам:
- на этой полочке книги по алгебре
- на этой полочке книги по геометрии
- на этой полочке книги по матанализу
- и т.д.
Так вот в Java есть виртуальная библиотека протестированного кода — это уже готовые решения ко многим задачам, которые стоят перед программистами в их ежедневной работе. То есть бери код из библиотеки и используй. А это очень и очень экономит время программиста, потому что не надо писать абсолютно весь код с нуля.
В этой виртуальной библиотеке Java информация разбита по пакетам («packages») — это своеобразный аналог полочек в книжном магазине. В каждом пакете протестированный код по какому-то отдельно взятому направлению.
Например, есть такие пакеты:
- java.applet
- java.lang — это основной пакет языка Java
- java.util
- java.io
- java.net
- и т.д.
Если совсем любопытно, все пакеты Вы можете найти на сайте Oracle по ссылке: https://docs.oracle.com/javase/8/docs/api
Давайте посмотрим на схематическое изображение библиотеки в Java.
Как видите, слева изображены разные пакеты («packages»):
А что же в каждом пакете? В пакете лежат классы . Чтобы проиллюстрировать это, мы показали на примере пакета java.lang. Для примера на схеме изображён один из классов пакета java.lang — класс Math.
Детально что такое классы мы разберём в отдельной статье, когда мы с Вами дойдём до темы объектно-ориентированного программирования (ООП) в Java. А сейчас Вам будет достаточно понимать, что класс — это готовое решение, которое мы можем использовать при написании наших программ.
В классе есть методы (действия), которые мы можем выполнять с помощью класса. Например, в классе Math есть такие методы:
- sqrt () — выведение квадратного корня
- sin () — вычисление синуса угла
- cos () — вычисление косинуса угла
- и т.д.
То есть, если нам необходимо посчитать квадратный корень, нам не надо писать код, который пошагово программировал бы вычисление квадратного корня. А такой код бы потянул на очень и очень много строк кода. А мы просто берём из пакета java.lang класс Math, а в нём метод который нам нужен для вычисления квадратного корня sqrt () и всё — в одну строчку кода мы получим нужное нам решение.
Надеюсь, теперь Вам понятно, что такое библиотека в Java, какая у нее структура и что готовые решения из библиотеки очень экономят программистам драгоценное рабочее время.
Постепенно Вы познакомитесь с различными классами и их методами из библиотеки Java, и главное — как же их использовать в своём коде. А пока нам важно было очень обзорно понять данную тему. И данную миссию мы с Вами выполнили.
Надеемся, что наша статья была Вам полезна. Также есть возможность записаться на наши курсы по Java в Киеве. Обучаем с нуля. Детальную информацию Вы можете найти у нас на сайте.
- java : Root package for library core