Что такое аннотация в java
Перейти к содержимому

Что такое аннотация в java

  • автор:

Annotations Basics

In its simplest form, an annotation looks like the following:

The at sign character ( @ ) indicates to the compiler that what follows is an annotation. In the following example, the annotation’s name is Override :

The annotation can include elements, which can be named or unnamed, and there are values for those elements:

If there is just one element named value , then the name can be omitted, as in:

If the annotation has no elements, then the parentheses can be omitted, as shown in the previous @Override example.

It is also possible to use multiple annotations on the same declaration:

If the annotations have the same type, then this is called a repeating annotation:

Repeating annotations are supported as of the Java SE 8 release. For more information, see Repeating Annotations.

The annotation type can be one of the types that are defined in the java.lang or java.lang.annotation packages of the Java SE API. In the previous examples, Override and SuppressWarnings are predefined Java annotations. It is also possible to define your own annotation type. The Author and Ebook annotations in the previous example are custom annotation types.

Where Annotations Can Be Used

Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements. When used on a declaration, each annotation often appears, by convention, on its own line.

As of the Java SE 8 release, annotations can also be applied to the use of types. Here are some examples:

  • Class instance creation expression:
  • Type cast:
  • implements clause:
  • Thrown exception declaration:

This form of annotation is called a type annotation. For more information, see Type Annotations and Pluggable Type Systems.

Annotations

This section explains where annotations can be used, how to apply annotations, what predefined annotation types are available in the Java Platform, Standard Edition (Java SE API), how type annotations can be used in conjunction with pluggable type systems to write code with stronger type checking, and how to implement repeating annotations.

The Format of an Annotation

In its simplest form, an annotation looks like the following:

The at sign character ( @ ) indicates to the compiler that what follows is an annotation. In the following example, the annotation's name is Override :

The annotation can include elements, which can be named or unnamed, and there are values for those elements:

If there is just one element named value , then the name can be omitted, as in:

If the annotation has no elements, then the parentheses can be omitted, as shown in the previous @Override example.

It is also possible to use multiple annotations on the same declaration:

If the annotations have the same type, then this is called a repeating annotation:

Repeating annotations are supported as of the Java SE 8 release. For more information, see the section Repeating Annotations.

The annotation type can be one of the types that are defined in the java.lang or java.lang.annotation packages of the Java SE API. In the previous examples, Override and SuppressWarnings are predefined Java annotations. It is also possible to define your own annotation type. The Author and Ebook annotations in the previous example are custom annotation types.

Where Annotations Can Be Used

Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements. When used on a declaration, each annotation often appears, by convention, on its own line.

As of the Java SE 8 release, annotations can also be applied to the use of types. Here are some examples:

Class instance creation expression:

Thrown exception declaration:

This form of annotation is called a type annotation.

Declaring an Annotation Type

Many annotations replace comments in code.

Suppose that a software group traditionally starts the body of every class with comments providing important information:

To add this same metadata with an annotation, you must first define the annotation type. The syntax for doing this is:

The annotation type definition looks similar to an interface definition where the keyword interface is preceded by the at sign ( @ ) ( @ = AT, as in annotation type). Annotation types are a form of interface, which will be covered in a later section. For the moment, you do not need to understand interfaces.

The body of the previous annotation definition contains annotation type element declarations, which look a lot like methods. Note that they can define optional default values.

After the annotation type is defined, you can use annotations of that type, with the values filled in, like this:

Note: To make the information in @ClassPreamble appear in Javadoc-generated documentation, you must annotate the @ClassPreamble definition with the @Documented annotation:

Predefined Annotation Types

A set of annotation types are predefined in the Java SE API. Some annotation types are used by the Java compiler, and some apply to other annotations.

Annotation Types Used by the Java Language

The predefined annotation types defined in java.lang are @Deprecated , @Override , and @SuppressWarnings .

@Deprecated

@Deprecated annotation indicates that the marked element is deprecated and should no longer be used. The compiler generates a warning whenever a program uses a method, class, or field with the @Deprecated annotation. When an element is deprecated, it should also be documented using the Javadoc @deprecated tag, as shown in the following example. The use of the at sign ( @ ) in both Javadoc comments and in annotations is not coincidental: they are related conceptually. Also, note that the Javadoc tag starts with a lowercase d and the annotation starts with an uppercase D .

Note that, as of Java SE 9, a forRemoval attribute has been added to the @Deprecated annotation. It indicates whether the annotated element is subject to removal in a future version. The default value is false .

@Override

@Override annotation informs the compiler that the element is meant to override an element declared in a superclass. Overriding methods will is discussed in the section Interfaces and Inheritance.

While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.

@SuppressWarnings

@SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate. In the following example, a deprecated method is used, and the compiler usually generates a warning. In this case, however, the annotation causes the warning to be suppressed.

Every compiler warning belongs to a category. The Java Language Specification lists two categories: deprecation and unchecked. The unchecked warning can occur when interfacing with legacy code written before the advent of generics. To suppress multiple categories of warnings, use the following syntax:

@SafeVarargs

@SafeVarargs annotation, when applied to a method or constructor, asserts that the code does not perform potentially unsafe operations on its varargs parameter. When this annotation type is used, unchecked warnings relating to varargs usage are suppressed.

@FunctionalInterface

@FunctionalInterface annotation, introduced in Java SE 8, indicates that the type declaration is intended to be a functional interface, as defined by the Java Language Specification.

Annotations That Apply to Other Annotations

Annotations that apply to other annotations are called meta-annotations. There are several meta-annotation types defined in java.lang.annotation .

@Retention

@Retention annotation specifies how the marked annotation is stored:

    – The marked annotation is retained only in the source level and is ignored by the compiler. – The marked annotation is retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM). – The marked annotation is retained by the JVM so it can be used by the runtime environment.
@Documented

@Documented annotation indicates that whenever the specified annotation is used those elements should be documented using the Javadoc tool. (By default, annotations are not included in Javadoc.) For more information, see the Javadoc tools page.

@Target

@Target annotation marks another annotation to restrict what kind of Java elements the annotation can be applied to. A target annotation specifies one of the following element types as its value:

    can be applied to an annotation type. can be applied to a constructor. can be applied to a field or property. can be applied to a local variable. can be applied to a method-level annotation. can be applied to a module declaration. can be applied to a package declaration. can be applied to the parameters of a method. can be applied to the component of a record. can be applied to the declaration of a class, an abtract class, an interface, an annotation interface, an enumeration, or a record declaration. can be applied on the parameters of a type. can be applied where a type is used, for instance on the declaration of a field.
@Inherited

@Inherited annotation indicates that the annotation type can be inherited from the super class. (This is not true by default.) When the user queries the annotation type and the class has no annotation for this type, the class' superclass is queried for the annotation type. This annotation applies only to class declarations.

@Repeatable

@Repeatable annotation, introduced in Java SE 8, indicates that the marked annotation can be applied more than once to the same declaration or type use. For more information, see the section Repeating Annotations.

Type Annotations and Pluggable Type Systems

Before the Java SE 8 release, annotations could only be applied to declarations. As of the Java SE 8 release, annotations can also be applied to any type use. This means that annotations can be used anywhere you use a type. A few examples of where types are used are class instance creation expressions ( new ), casts, implements clauses, and throws clauses. This form of annotation is called a type annotation and several examples are provided in the section Annotations Basics.

Type annotations were created to support improved analysis of Java programs way of ensuring stronger type checking. The Java SE 8 release does not provide a type checking framework, but it allows you to write (or download) a type checking framework that is implemented as one or more pluggable modules that are used in conjunction with the Java compiler.

For example, you want to ensure that a particular variable in your program is never assigned to null; you want to avoid triggering a NullPointerException . You can write a custom plug-in to check for this. You would then modify your code to annotate that particular variable, indicating that it is never assigned to null. The variable declaration might look like this:

When you compile the code, including the NonNull module at the command line, the compiler prints a warning if it detects a potential problem, allowing you to modify the code to avoid the error. After you correct the code to remove all warnings, this particular error will not occur when the program runs.

You can use multiple type-checking modules where each module checks for a different kind of error. In this way, you can build on top of the Java type system, adding specific checks when and where you want them.

With the judicious use of type annotations and the presence of pluggable type checkers, you can write code that is stronger and less prone to error.

In many cases, you do not have to write your own type checking modules. There are third parties who have done the work for you. For example, you might want to take advantage of the Checker Framework created by the University of Washington. This framework includes a NonNull module, as well as a regular expression module, and a mutex lock module. For more information, see the Checker Framework.

Repeating Annotations

There are some situations where you want to apply the same annotation to a declaration or type use. As of the Java SE 8 release, repeating annotations enable you to do this.

For example, you are writing code to use a timer service that enables you to run a method at a given time or on a certain schedule, similar to the UNIX cron service. Now you want to set a timer to run a method, doPeriodicCleanup() , on the last day of the month and on every Friday at 11:00 p.m. To set the timer to run, create an @Schedule annotation and apply it twice to the doPeriodicCleanup() method. The first use specifies the last day of the month and the second specifies Friday at 11p.m., as shown in the following code example:

The previous example applies an annotation to a method. You can repeat an annotation anywhere that you would use a standard annotation. For example, you have a class for handling unauthorized access exceptions. You annotate the class with one @Alert annotation for managers and another for admins:

For compatibility reasons, repeating annotations are stored in a container annotation that is automatically generated by the Java compiler. In order for the compiler to do this, two declarations are required in your code.

Step 1: Declare a Repeatable Annotation Type

The annotation type must be marked with the @Repeatable meta-annotation. The following example defines a custom @Schedule repeatable annotation type:

The value of the @Repeatable meta-annotation, in parentheses, is the type of the container annotation that the Java compiler generates to store repeating annotations. In this example, the containing annotation type is @Schedules , so repeating @Schedule annotations is stored in an @Schedules annotation.

Applying the same annotation to a declaration without first declaring it to be repeatable results in a compile-time error.

Step 2: Declare the Containing Annotation Type

The containing annotation type must have a value element with an array type. The component type of the array type must be the repeatable annotation type. The declaration for the @Schedules containing annotation type is the following:

Retrieving Annotations

There are several methods available in the Reflection API that can be used to retrieve annotations. The behavior of the methods that return a single annotation, such as AnnotatedElement.getAnnotation(Class<T>) , are unchanged in that they only return a single annotation if one annotation of the requested type is present. If more than one annotation of the requested type is present, you can obtain them by first getting their container annotation. In this way, legacy code continues to work. Other methods were introduced in Java SE 8 that scan through the container annotation to return multiple annotations at once, such as AnnotatedElement.getAnnotationsByType(Class<T>) . See the AnnotatedElement class specification for information on all of the available methods.

Design Considerations

When designing an annotation type, you must consider the cardinality of annotations of that type. It is now possible to use an annotation zero times, once, or, if the annotation's type is marked as @Repeatable , more than once. It is also possible to restrict where an annotation type can be used by using the @Target meta-annotation. For example, you can create a repeatable annotation type that can only be used on methods and fields. It is important to design your annotation type carefully to ensure that the programmer using the annotation finds it to be as flexible and powerful as possible.

Java @Аннотации. Что это и как этим пользоваться?

Java @Аннотации. Что это и как этим пользоваться? - 1

Данная статья предназначена для людей, которые никогда не работали с Аннотациями, но хотели бы разобраться, что это и с чем его едят. Если же вы имеете опыт в данной сфере, не думаю, что эта статья как-то расширит ваши знания (да и, собственно, такую цель я не преследую). Также статья не подходит для тех, кто только начинает изучать язык Java. Если Вы не понимаете что такое Map<> или HashMap<> или не знаете что означает запись static < >внутри определения класса, либо же никогда не работали с рефлексией – Вам рано читать эту статью и пытаться понять, что такое аннотации. Сам по себе этот инструмент не создан для использования новичками, так как требует уже не совсем базовых пониманий взаимодействия классов и объектов (моё мнение) (спасибо комментариям за то, что показали необходимость этой приписки). Итак, приступим. Аннотации в Java являются своего рода метками в коде, описывающими метаданные для функции/класса/пакета. Например, всем известная Аннотация @Override, обозначающая, что мы собираемся переопределить метод родительского класса. Да, с одной стороны, можно и без неё, но если у родителей не окажется этого метода, существует вероятность, что мы зря писали код, т.к. конкретно этот метод может и не вызваться никогда, а с Аннотацией @Override компилятор нам скажет, что: «Я не нашел такого метода в родителях. что-то здесь нечисто». Однако Аннотации могут нести в себе не только смысл «для надежности»: в них можно хранить какие-то данные, которые после будут использоваться.

Аннотации в Java и их обработка

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

Помимо использования стандартных аннотаций из пакета java.lang, о которых мы поговорим далее, можно также создавать свои аннотации и обрабатывать их.

В этой статье мы обсудим назначение стандартных аннотаций, а также рассмотрим на практическом примере создание и обработку своих аннотаций.

Код примеров вы можете найти на GitHub.

Основы аннотаций

Аннотации начинаются с символа @ . Например, в пакете java.lang определены аннотации @Override и @SuppressWarnings .

Сама по себе аннотация не выполняет никаких действий. Она просто предоставляет информацию, которую можно использовать во время компиляции или в рантайме.

В качестве примера рассмотрим аннотацию @Override :

Аннотация @Override используется для обозначения переопределенного метода из базового класса. Приведенная выше программа при компиляции выдаст ошибку, потому что метод getname() в классе ChildClass аннотирован @Override , но в родительском классе ParentClass метода getname() нет.

Используя аннотацию @Override в ChildClass , компилятор проверяет, что имя переопределенного метода в дочернем классе совпадает с именем метода в родительском классе.

Стандартные аннотации

Рассмотрим некоторые из распространенных стандартных аннотаций из пакета java.lang . Чтобы увидеть их влияние на поведение компилятора, запускайте примеры из командной строки, поскольку большинство IDE могут подавлять предупреждения.

@SuppressWarnings

Аннотация @SuppressWarnings используется для подавления предупреждений компилятора. Например, @SuppressWarnings («unchecked») отключает предупреждения, связанные с «сырыми» типами (Raw Types).

Давайте рассмотрим пример использования @SuppressWarnings :

Если мы запустим компиляцию из командной строки с параметром -Xlint:unchecked , то получим следующее сообщение:

Это пример легаси кода (до Java 5) — в коллекции мы можем случайно сохранить объекты разных типов. Для проверки подобных ошибок на этапе компиляции, были придуманы обобщенные типы (generics, дженерики). Чтобы этот код компилировался без предупреждений измените строку:

Если подобного легаси кода много, то вы вряд ли захотите вносить изменения, поскольку это влечет за собой много регрессионного тестирования. В этом случае к классу можно добавить аннотацию @SuppressWarning , чтобы логи не загромождались избыточными предупреждениями.

Теперь при компиляции предупреждений не будет.

@Deprecated

Аннотация @Deprecated используется для пометки устаревших методов или типов.

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

В примере ниже метод testLegacyFunction() помечен как устаревший:

В атрибуте since этой аннотации содержится версия, с которой элемент объявлен устаревшим, а forRemoval указывает, будет ли элемент удален в следующей версии.

Теперь вызов устаревшего метода, вызовет предупреждение во время компиляции, указывая, что лучше этот метод не использовать:

@Override

Мы уже упоминали выше аннотацию @Override . Она используется для проверки переопределенных методов во время компиляции на такие ошибки, как опечатки в регистре символов:

Здесь мы хотели переопределить метод getEmployeeStatus() , но неправильно написали имя метода. Это может привести к серьезным ошибкам. Приведенная выше программа скомпилируется и запуститься без проблем, не обнаружив эту ошибку при компиляции.

Если добавить аннотацию @Override к методу getemployeeStatus() , то при компиляции получим следующую ошибку:

@FunctionalInterface

Аннотация @FunctionalInterface используется для указания того, что в интерфейсе не может быть более одного абстрактного метода. Если абстрактных методов будет больше одного, то компилятор выдаст ошибку. Функциональные интерфейсы появились в Java 8 для реализации лямбда-выражений и гарантии того, что в них не более одного абстрактного метода.

Но и без аннотации @FunctionalInterface компилятор выдаст ошибку, если вы включите в интерфейс больше одного абстрактного метода. Так зачем же нужна необязательная аннотация @FunctionalInterface ?

Давайте рассмотрим следующий пример:

Если в интерфейс Print мы добавим еще один метод printString2() , то компилятор или IDE выдаст ошибку.

А что, если интерфейс Print находится в отдельном модуле и без аннотации @FunctionalInterface ? Разработчики этого модуля могут легко добавить в интерфейс еще один метод и сломать ваш код. Добавив аннотацию @FunctionalInterface , мы сразу получим предупреждение в IDE:

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

@SafeVarargs

Функциональность varargs позволяет создавать методы с переменным количеством аргументов. До Java 5 единственной возможностью создания методов с необязательными параметрами было создание нескольких методов, каждый из которых с разным количеством параметров. Varargs позволяет создать один метод с переменным количеством параметров с помощью следующего синтаксиса:

Однако при использовании в аргументах метода обобщенных типов выдаются предупреждения. Аннотация @SafeVarargs позволяет подавить их:

Методы printString() и printStringVarargs() приводят к одинаковому результату. Но при компиляции для метода printStringSafeVarargs() выдается предупреждение, поскольку в нем используются обобщенные типы:

Добавив аннотацию @SafeVarargs , мы можем избавиться от этого предупреждения:

Пользовательские аннотации

Мы можем создавать свои аннотации, например, для реализации следующей функциональности:

Уменьшение дублирования кода.

Автоматизация генерации бойлерплейт кода.

Отлов ошибок во время компиляции, например, потенциальные Null Pointer Exception.

Настройка поведения в рантайме на основе наличия аннотации.

Для примера рассмотрим аннотацию @Company :

При создании экземпляров класса CustomAnnotatedEmployee все экземпляры будут содержать одно и то же название компании (name) и города (city) — больше не нужно добавлять эту информацию в конструктор.

Создать пользовательскую аннотацию можно с помощью ключевого слова @interface :

Чтобы указать информацию об области действия аннотации и о типах элементов, к которым она может быть применена, используются мета-аннотации.

Например, чтобы указать, что аннотация применяется только к классам, используется аннотация @Target(ElementType.TYPE) . А мета-аннотация @Retention(RetentionPolicy.RUNTIME) указывает, что аннотация должна быть доступна в рантайме.

С мета-аннотациями наша аннотация @Company выглядит следующим образом:

Далее добавим атрибуты в нашу аннотацию: имя ( name ) и город ( city ). Добавляем их, как показано ниже:

Создадим класс CustomAnnotatedEmployee и применим к нему аннотацию @Company :

Прочитать аннотацию @Company в рантайме можно следующим образом:

Результат будет следующий:

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

Мета-аннотации

Мета-аннотации — это аннотации, применяемые к другим аннотациям для предоставления информации об аннотации компилятору или среде выполнения.

Мета-аннотации могут ответить на следующие вопросы об аннотации:

Может ли аннотация наследоваться дочерними классами?

Должна ли аннотация отображаться в документации?

Можно ли применить аннотацию несколько раз к одному и тому же элементу?

К какому типу элементов можно применить аннотацию: к классу, методу, полю и т.д.?

Обрабатывается ли аннотация во время компиляции или в рантайме?

@Inherited

По умолчанию аннотация не наследуется от родительского класса к дочернему. Мета-аннотация @Inherited позволяет ей наследоваться:

Поскольку CustomAnnotatedEmployee аннотирован @Company , а CustomAnnotatedManager наследуется от него, то нет необходимости ставить аннотацию на класс CustomAnnotatedManager .

Давайте проверим это.

Аннотация @Company доступна, хотя мы не указывали ее явно для класса Manager .

@Documented

@Documented указывает, что аннотация должна присутствовать в JavaDoc.

По умолчанию информация об аннотациях не отображается в JavaDoc-документации, но если использовать @Documented, она появится:

@Repeatable

@Repeatable позволяет использовать аннотацию несколько раз на одном методе, классе или поле. Для использования @Repeatable — аннотации необходимо создать аннотацию-контейнер, которая хранит значение в виде массива исходных аннотаций:>

Использовать аннотацию можно следующим образом:

Получим следующий результат, отображающий значение нескольких аннотаций @RepeatableCompany :

@Target

@Target определяет типы элементов, к которым может применяться аннотация. Например, в приведенном выше примере аннотация @Company была определена как TYPE, и поэтому может быть применена только к классам.

Давайте попробуем применить аннотацию @Company к методу:

В этом случае мы получим ошибку компилятора: @Company not applicable to method .

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

@Retention

@Retention указывает, когда аннотация будет доступна:

SOURCE — аннотация доступна в исходном коде и удаляется после компиляции.

CLASS — аннотация сохраняется в class-файле во время компиляции, но недоступна при выполнении программы.

RUNTIME — аннотация доступна в рантайме.

Если аннотация нужна только для проверки ошибок во время компиляции, как это делает @Override , мы используем SOURCE. Если аннотация нужна для обеспечения функциональности в рантайме, например, @Test в JUnit, то используем RUNTIME. Давайте поэкспериментируем с разными значениями RetentionPolicy :

Создадим класс, который использует все три аннотации:

Для проверки доступности аннотаций запустите следующий код:

Результат будет следующим:

Итак, мы убедились, что в рантайме доступна только RUNTIME-аннотация.

Классификация аннотаций

Аннотации можно классифицировать по количеству передаваемых в них параметров: без параметров, с одним параметром и с несколькими параметрами.

Маркерные аннотации

Маркерные аннотации не содержат никаких членов или данных. Для определения наличия аннотации можно использовать метод isAnnotationPresent() .

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

Класс Client может использовать аннотацию следующим образом:

Обработать аннотацию можно следующим образом:

На основании присутствия аннотации @CSV , мы можем решить, куда записать информацию — в CSV или в файл Excel. Приведенная выше программа выдаст следующий результат:

Аннотации с одним значением

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

Давайте создадим аннотацию SingleValueAnnotationCompany с одним атрибутом value :

Создайте класс, использующий аннотацию:

Запустите следующий пример:

Переданное значение «XYZ» переопределяет значение атрибута аннотации по умолчанию. Результат выглядит следующим образом:

Полные аннотации

Они состоят из нескольких пар «имя-значение». Например, Company(name = «ABC», city = «XYZ») . Рассмотрим наш исходный пример Company:

Давайте создадим класс MultiValueAnnotatedEmployee со значением параметров, как показано ниже. Значения по умолчанию будут перезаписаны.

Запустите следующий пример:

Практический пример

В качестве практического примера обработки аннотаций напишем простой аналог аннотации @Test из JUnit. Пометив методы аннотацией @Test , мы сможем определить в рантайме, какие методы тестового класса нужно запускать как тесты.

Сначала создадим маркерную аннотацию для методов-тестов:

Далее создадим класс AnnotatedMethods , в котором применим аннотацию @Test к методу test1() . Это позволит выполнить метод в рантайме. У метода test2() аннотации нет и он не должен выполняться.

Теперь напишем код для запуска тестов из класса AnnotatedMethods :

Через метод getDeclaredMethods() мы получаем методы класса AnnotatedMethods . Затем перебираем методы и проверяем, аннотирован ли метод аннотацией @Test . Наконец, выполняем вызов методов, которые были аннотированы с помощью @Test .

В результате метод test1() выполнится, поскольку он аннотирован @Test , а test2() нет, так как он без аннотации @Test .

Заключение

Мы сделали обзор основных стандартных аннотаций и рассмотрели, как создавать и обрабатывать свои аннотации.

Возможностей по использованию аннотаций гораздо больше, чем мы рассмотрели. Например, можно автоматически генерировать код для паттерна Builder. Шаблон проектирования Builder (строитель) используется как альтернатива конструкторам, когда в конструкторы передается много параметров или есть необходимость в нескольких конструкторах с необязательными параметрами. При большом количестве таких классов возможность генерации кода обработчиком аннотаций сэкономит много времени и поможет избежать дублирования кода.

Примеры кода вы можете найти на GitHub.

Всех желающих приглашаем на Demo-занятие «Объектно-ориентированное и функциональное программирование». На вебинаре поговорим о стилях программирования и необходимости каждого из них. Разберём основные принципы объектно-ориентированного стиля (Инкапсуляция, Наследование, Полиморфизм), а также возможности функционального стиля, которые предоставляет язык Java. Регистрация для всех желающих по ссылке.

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

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