Java annotation class extends

Interface Annotation

The common interface extended by all annotation interfaces. Note that an interface that manually extends this one does not define an annotation interface. Also note that this interface does not itself define an annotation interface. More information about annotation interfaces can be found in section 9.6 of The Java Language Specification . The AnnotatedElement interface discusses compatibility concerns when evolving an annotation interface from being non-repeatable to being repeatable.

Method Summary

Returns true if the specified object represents an annotation that is logically equivalent to this one.

Method Details

equals

  • Two corresponding primitive typed members whose values are x and y are considered equal if x == y , unless their type is float or double .
  • Two corresponding float members whose values are x and y are considered equal if Float.valueOf(x).equals(Float.valueOf(y)) . (Unlike the == operator, NaN is considered equal to itself, and 0.0f unequal to -0.0f .)
  • Two corresponding double members whose values are x and y are considered equal if Double.valueOf(x).equals(Double.valueOf(y)) . (Unlike the == operator, NaN is considered equal to itself, and 0.0 unequal to -0.0 .)
  • Two corresponding String , Class , enum, or annotation typed members whose values are x and y are considered equal if x.equals(y) . (Note that this definition is recursive for annotation typed members.)
  • Two corresponding array typed members x and y are considered equal if Arrays.equals(x, y) , for the appropriate overloading of Arrays.equals .

hashCode

  • The hash code of a primitive value v is equal to WrapperType.valueOf(v).hashCode() , where WrapperType is the wrapper type corresponding to the primitive type of v ( Byte , Character , Double , Float , Integer , Long , Short , or Boolean ).
  • The hash code of a string, enum, class, or annotation member-value v is computed as by calling v.hashCode() . (In the case of annotation member values, this is a recursive definition.)
  • The hash code of an array member-value is computed by calling the appropriate overloading of Arrays.hashCode on the value. (There is one overloading for each primitive type, and one for object reference types.)
Читайте также:  Color picker for css

toString

Returns a string representation of this annotation. The details of the representation are implementation-dependent, but the following may be regarded as typical:

@com.example.Name(first="Duke", middle="of", last="Java")

annotationType

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Аннотации в JAVA: обзор синтаксиса и создание собственных

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

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

Синтаксис

Аннотация задается описанием соответствующего интерфейса.
Например так:

import java.lang.annotation.*; @Target(value=ElementType.FIELD) @Retention(value= RetentionPolicy.RUNTIME) public @interface Name

Как видно из примера выше, аннотация определяется описанием с ключевым словом interface и может включать в себя несколько полей, которые можно задать как обязательными, так и не обязательными. В последнем случае подставляется default значение поля.
Также из примера видно, что саму аннотацию можно пометить несколькими аннотациями.
Разберемся для начала, чем можно пометить собственную аннотацию, и зачем.

Аннотация @Retention позволяет указать жизненный цикл аннотации: будет она присутствовать только в исходном коде, в скомпилированном файле, или она будет также видна и в процессе выполнения. Выбор нужного типа зависит от того, как вы хотите использовать аннотацию, например, генерировать что-то побочное из исходных кодов, или в процессе выполнения стучаться к классу через reflection.

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

Аннотация @Documentedуказывает, что помеченная таким образом аннотация должна быть добавлена в javadoc поля/метода и т.д.
Например, класс, помеченный аннотацией без @Documented, будет выглядеть так:

public class TestClass extends java.lang.Object

А если в описание аннотации добавить @Documented, получим:

@ControlledObject(name="name") public class TestClass extends java.lang.Object

Аннотация @Inherited помечает аннотацию, которая будет унаследована потомком класса, отмеченного такой аннотацией.
Сделаем для примера пару аннотаций и пометим ими класс.

@Inherited @interface PublicAnnotate < >@interface PrivateAnnotate < >@PublicAnnotate @PrivateAnnotate class ParentClass < >class ChildClass extends ParentClass

Класс ChildClass унаследует от родительского класса только аннотацию PublicAnnotate.

Пример своей аннотации.

Попробуем теперь написать рабочий пример с использованием аннотаций.
Представим себе, что у нас есть какой-то самодельный проект, который на вход получает класс, специально заанотированный, чтобы проект мог управлять жизненным циклом объектов этого класса, и пусть там будут аннотации StartObject, StopObject для описания методов класса, и ControlledObject для описания самого класса. Последней аннотации дадим еще поле name, путь там хранится якобы имя для поиска.
Аннотации будут выглядеть так:

@Target(value=ElementType.METHOD) @Retention(value= RetentionPolicy.RUNTIME) public @interface StartObject < >@Target(value=ElementType.METHOD) @Retention(value= RetentionPolicy.RUNTIME) public @interface StopObject < >@Target(value=ElementType.TYPE) @Retention(value= RetentionPolicy.RUNTIME) public @interface ControlledObject

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

@ControlledObject(name="biscuits") public class Cookies < @StartObject public void createCookie()< //бизнес логика >@StopObject public void stopCookie() < //бизнес логика >>

Для того, чтобы работать с классом, сначала необходимо загрузить класс в контекст приложения. Используем:
Class cl = Class.forName(«org.annotate.test.classes.Cookies»);
Далее, через механизм reflection мы получаем доступ к полям и аннотациям класса.
Проверим наличие аннотированных методов в классе и аннотации на самом классе:

if(!cl.isAnnotationPresent(ControlledObject.class)) < System.err.println("no annotation"); >else < System.out.println("class annotated ; name - " + cl.getAnnotation(ControlledObject.class)); >boolean hasStart=false; boolean hasStop=false; Method[] method = cl.getMethods(); for(Method md: method) < if(md.isAnnotationPresent(StartObject.class)) if(md.isAnnotationPresent(StopObject.class)) if(hasStart && hasStop) > System.out.println("Start annotaton - " + hasStart + "; Stop annotation - " + hasStop ); 

Запустив, на выходе мы получим:
Start annotaton — true; Stop annotation — true.
Если попробовать убрать одну из аннотаций, то вывод сообщит о несоответствии требованиям.

Итог

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

Подробнее ознакомиться с данным механизмом могу порекомендовать в книге «Java 2. Библиотека профессионала, том 2. Тонкости программирования» Кей С. Хорстманна, Гари Корнелла, или на сайте oracle, где так же есть подробные туториалы.

Источник

Java Annotation Inheritance

I ran into an issue recently with Java, where I had two classes, one extending from the other, and an annotation attached to the super class.

I was reflecting to see if I could see the annotation applied, but it was wasn’t there! Here are my findings, and my solution to:

How can your subclasses inherit the super classes annotations?

java.lang.Inherited

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
public class Main  public static void main(String . args)  A a = new A(); B b = new B(); System.out.println(a.getClass().isAnnotationPresent(Annotation.class)); System.out.println(b.getClass().isAnnotationPresent(Annotation.class)); > > @Annotation class A <> class B extends A <> @Retention(RetentionPolicy.RUNTIME) @Inherited // @interface Annotation <> 

Console Output:

Источник

Оцените статью