- Файл package-info.java
- 2. Назначение package-info
- 3. Пакет документации
- 4. Аннотации пакетов
- 5. Как создать файл с информацией о пакете
- 6. Заключение
- What’s package-info.java for?
- How do I add package level annotations or edit package-info.java?
- How do I add package level annotations or edit package-info.java?
- package-info.java
- What is JAXB generated package-info.java
- Eclipse Juno — What is the use of package-info.java?
- Maven: Compiling package-info.java to package-info.class?
Файл package-info.java
В этом руководстве мы поймем назначение package-info.java и его полезность. Проще говоря, package-info — это файл Java, который можно добавить в любой пакет Java .
2. Назначение package-info
В настоящее время файл package-info.java служит двум целям:
Помимо вышеупомянутого, варианты использования могут быть расширены по мере необходимости. В будущем, если потребуется добавить какую-либо функцию на уровне пакета, этот файл будет идеальным местом.
Давайте подробно рассмотрим текущие варианты использования.
3. Пакет документации
До версии Java 5 документация, относящаяся к пакету, помещалась в HTML-файл package.html . Это обычный файл HTML с комментариями Javadoc, размещенными внутри тега body .
Когда JDK 5 появился на сцене, package.html уступил место новому параметру package-info.java , который теперь предпочтительнее package.html .
Давайте посмотрим на пример документации пакета в файле package-info.java :
/** * This module is about impact of the final keyword on performance * * This module explores if there are any performance benefits from * using the final keyword in our code. This module examines the performance * implications of using final on a variable, method, and class level. * * * @since 1.0 * @author foreach * @version 1.1 */ package com.foreach.finalkeyword;
Приведенный выше package-info.java сгенерирует Javadoc:
Итак, так же, как мы пишем Javadoc в других местах, мы можем поместить пакет Javadoc в исходный файл Java.
4. Аннотации пакетов
Предположим, нам нужно применить аннотацию ко всему пакету . В этом случае нам может прийти на помощь package-info.java .
Рассмотрим ситуацию, когда нам нужно объявить поля, параметры и возвращаемые значения ненулевыми по умолчанию. Мы можем достичь этой цели, просто включив аннотацию @NonNullApi для ненулевых параметров и возвращаемых значений, ` а также аннотацию @NonNullFields для ненулевых полей в наш файл package-info.java .`
@NonNullFields и @NonNullApi будут помечать поля, параметры и возвращаемые значения как ненулевые, если они явно не помечены как @Nullable :
@NonNullApi @NonNullFields package com.foreach.nullibility; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
Существуют различные аннотации, которые можно использовать на уровне пакета. Например, в проекте Hibernate у нас есть категория аннотаций , а в проекте JAXB также есть аннотации уровня пакета .
5. Как создать файл с информацией о пакете
Создать файл с информацией о пакете довольно просто: мы можем создать его вручную или обратиться за помощью в IDE для его создания.
В IntelliJ IDEA мы можем щелкнуть правой кнопкой мыши пакет и выбрать New->package-info.java :
Опция Eclipse New Java Package позволяет нам сгенерировать package-info.java :
Вышеупомянутый метод работает и для существующих пакетов. Выберите существующий пакет, выберите опцию New-> Package и отметьте опцию Create package-info.java .
Хорошей практикой всегда является обязательное включение package-info.java в правила кодирования наших проектов. В этом могут помочь такие инструменты, как Sonar или Checkstyle .
6. Заключение
Основное различие между использованием файлов HTML и Java заключается в том, что с файлом Java у нас есть дополнительная возможность использования аннотаций Java. Таким образом , java- файл с информацией о пакете является не только домом для пакета Javadocs, но и аннотаций для всего пакета . Кроме того, этот список вариантов использования может быть расширен в будущем .
What’s package-info.java for?
In some recent classes, my students have encountered a package-info.java file tucked inside of some of the sample code we get from courseware providers. “What’s that thing?”, they usually ask.
package-info.java’s purpose
The package-info.java is a Java file that can be added to any Java source package. Its purpose is to provide a home for package level documentation and package level annotations. Simply create the package-info.java file and add the package declaration that it relates to in the file. In fact, the only thing the package-info.java file must contain is the package declaration.
package com.intertech.services;
The package-info.java file above must sit in the com.intertech.services package.
Package Documentation
Prior to Java 5, package level documentation (the documentation shown in Javadocs for a package) was placed in package.html. Today, the description and other related documentation for a package can be written up in the package-info.java file and it gets used in the production of the Javadocs. As a demonstration, the example package-info.java…
/** * Domain classes used to produce the JSON and XML output for the RESTful services. ** These classes contain the JAXB annotations. * * @since 1.0 * @author jwhite * @version 1.1 */ package com.intertech.cms.domain;
… results in the following Javadocs.
Package Annotations
Perhaps more importantly to today’s annotation driven programmer, the package-info.java file contains package level annotations. An annotation with ElementType.PACKAGE as one of its targets is a package-level annotation and there are many of them. Using your favorite IDE’s code assistant (shown in Eclipse below) in a package-info.java file and you will find a number package annotation options.
For example, perhaps you want to deprecate all the types in a package. You could annotate each individual type (the classes, interfaces, enums, etc. defined in their .java files) with @Deprecated (as shown below).
@Deprecated public class Contact
Or, you could use the @Deprecated on the package declaration in package-info.java. This has the effect of deprecating everything in the package in one fell swoop.
@Deprecated package com.intertech.cms.domain;
Help adding package-info.java to your packages
While you can add the package-info.java file to your packages by hand (just as you can create Java classes by hand), IDE’s often offer you the option to include a package-info.java file each time you create a new package. Eclipse, shown below, offers a simple (and often overlooked) checkbox in the New Java Package creation wizard.
Wrap Up
So now you know what that package-info.java file is all about and you know how to use it.
Like to learn more about Java or other Java related topics? Take a look at the that we provide.
Intertech also provides for those looking for some help with development projects. See what we can do for you!
How do I add package level annotations or edit package-info.java?
Solution 1: package-info.java is a way to apply java annotations at the package level. Solution 2: package-info.java file contains package level documentation as well as annotations.
How do I add package level annotations or edit package-info.java?
I’m trying to add package level annotations but I don’t have a clue on how to do it. Examples are appreciated.
Since package-info.java isn’t a valid identifier for a class it cannot be created as a class in Eclipse.
I found that when you create a new package there is a check box to check if you want a package-info.java.
To create a package-info. java file in an existing package:
- Right-click on the package where you want a package-info.java.
- Select New->Package.
- Check the Create package -info.java check box.
- Click on Finish.
Summary from the article here
@PackageLevelAnnotation package blammy; // package with a package level annotation. import blammy.annotation.PackageLevelAnnotation;
package blammy.annotation; @Retention(RetentionPolicy.CLASS) @Target(ElementType.PACKAGE) public @interface PackageLevelAnnotation < // stuff as required. >
Edit: more package level info. Here is a link to the package chapter in the java language spec : packages
package-info.java
The package-info.java is a Java file that can be added to any Java source package. Its purpose is to provide a home for package level documentation and package level annotations.
Simply create the package-info.java file. Add the package declaration in the file. In fact, the only thing the package-info.java file must contain is the package declaration.
Example of a minimal package info file:
package com.example.myapp.backend.data;
Example of a package-level annotation, @ParametersAreNonnullByDefault :
@ParametersAreNonnullByDefault package com.example.myapp.backend.data; import javax.annotation.ParametersAreNonnullByDefault;
For more info, see the Java specifications , in The Java® Language Specification , section 7.4.1 Named Packages .
Open explorer, go to src/your package folder.
right click -> Create new textfile: name it package-info.java.
Go back to eclipse and edit and add the desired content.
Maven — Why is package-info.java useful?, The package-info.java is a Java file that can be added to any Java source package. It is used to provide info at a «package» level as per its name. It contains documentation and annotations used in the package. javadoc example is already provided in the answer, the below part explains how it works incase of … Usage examplepackage com.domain;Feedback
What is JAXB generated package-info.java
I’m trying to find some information on what the package-info.java file generated by the JAXB xjc commandline app actually does. All that is in the file is
@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.example.com", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package the.generated.package.path;
What is this package-info.java file used for?
package-info.java is a way to apply java annotations at the package level. In this case Jaxb is using package-level annotations to indicate the namespace, and to specify namespace qualification for attributes (source).
This is also useful when you generate javadoc
package-info.java — Can contain a package declaration, package annotations, package comments and Javadoc tags. This file is new in JDK 5.0, and is preferred over package.html.
If you want to define default namespace for elements in your java model, you can define it in package-info.java
Javadoc: package.html or package-info.java, using package-info.java you can use <@link >and other doclets. When you link a java.lang class, when javadoc is generated you automatically get the <@link >pointing to the online javadoc of the class matching the jdk you are using; ide can also help to spot wrong links when you do refactoring refactoring.@link>
Eclipse Juno — What is the use of package-info.java?
When a new package is being created in Eclipse Juno, a java file (package -info.java) would be created automatically. What is the use of that file? Is it useful in importing specific classes in another class?
package-info.java is a package comment file, used by Javadoc for giving your package its own documentation.
It was introduced in Javadoc 5.0, and replaces package.html .
package-info.java file contains package level documentation as well as annotations.
It can be used for documentation on package level. For instance, the Spring Team uses it quite extensively in the core of the Spring Framework.
Beside that, it can contain annotations that apply to all classes in the package. For instance, it is a convenient way to avoid writing the NonNullByDefault annotations for the Eclipse Null Analysis on each class.
Note that for applying an annotation to a package, a file by the name package-info.java is used.
How do I add package level annotations or edit package, The package-info.java is a Java file that can be added to any Java source package. Its purpose is to provide a home for package level documentation and package level annotations. Simply create the package-info.java file. Add the package declaration in the file.
Maven: Compiling package-info.java to package-info.class?
I have package-info.java in my package, Hibernate wants it for some features (programatic entity scanning).
However, mvn package does not result in package-info.class being in classes/ thus not in the artifact.
How can I force that happening?
mvn -v Apache Maven 2.2.1 (r801777; 2009-08-06 21:16:01+0200) Java version: 1.6.0_26 Java home: /usr/lib/jvm/java-6-sun-1.6.0.26/jre Default locale: en_US, platform encoding: UTF-8 OS name: "linux" version: "2.6.35-30-generic" arch: "amd64" Family: "unix"
Give -Xpkginfo:always option to javac.
The error was that the package-info.java must have any annotation with Retention=RUNTIME to compile into a class. Otherwise, JDK 6 omits it.
I used @Deprecated which is the only one in Java SE (and I didn’t want to introduce an annotation just because of that).
@Deprecated package cz.zizka.ondra.packageinfo.test
Works correctly in Maven 3; don’t know about 2. Is it possible that the package declaration in package-info.java is missing or wrong?
What is JAXB generated package-info.java, 3 Answers. package-info.java is a way to apply java annotations at the package level. In this case Jaxb is using package-level annotations to indicate the namespace, and to specify namespace qualification for attributes (source). package-info.java — Can contain a package declaration, package annotations, …