Java – Annotations

Embed Size (px)

Citation preview

Java Annotations

Anotace v Jav

Martin Majli

Cl

Spojit dodatenou informaci s elementem programu

Snadnj drbaKd se d generovat

Kontrola chyb

Mnoh API potebuj dodaten soubory (Spring, hibernate, EJB 3, Seam, JAX-RPC)

Ukzka

class A { @Override public boolean equals(A a) { ... }@Deprecated public void myDeprecatedMethod() { ... }}Kompiltor: method does not override or implement a method from a supertype

Kompiltor: "The method myDeprecatedMethod() from the type A is deprecated."

Historie

JSR-175 Pedstaveno: 1. 4. 2002

Finln verze: 30. 9. 2004

http://www.jcp.org/en/jsr/detail?id=175

Poprv v JDK 1.5

Provizorn rozhran pro apt v JDK 1.5

JSR-269 formalizovno, integrovno do 1.6

Deklarace pklad - 1

public @interface Foo { }

public @interface RequestForEnhancement { int id(); String synopsis(); String engineer() default "[unassigned]"; String date() default "[unimplemented]";}

Deklarace gramatika 1

AnnotationTypeDeclaration: InterfaceModifiers @ interface Identifier AnnotationTypeBody AnnotationTypeBody: { AnnotationTypeElementDeclarations }

AnnotationTypeElementDeclarations: AnnotationTypeElementDeclaration AnnotationTypeElementDeclarations AnnotationTypeElementDeclaration

Deklarace gramatika 2

AnnotationTypeElementDeclaration: AbstractMethodModifiers Type Identifier ( ) DefaultValue ; ConstantDeclaration ClassDeclaration InterfaceDeclaration EnumDeclaration AnnotationTypeDeclaration ; DefaultValue: default ElementValue

Deklarace vlastnosti 1

Stejn jako interfaceMsto deklarace

Rozsah platnosti

Rozsah viditelnosti

Nesm bt generickm typem

Nesm obsahovat extends (implicitn dd od annotation.Annotation)

Libovoln poet element (0..*)

Deklarace vlastnosti 2

Nesm se pouvat zddn vlastnosti

Elementy mou mt defaultn hodnotu

Defaultn hodnota je z doby peten (ne kompilace)

Anotace T nesm obsahovat element typu T (pmo i nepmo)@interface SelfRef{ SelfRef value(); }

@interface Ping{ Pong value(); }

@interface Pong { Ping value(); }

Deklarace vlastnosti 3

Pmm pedkem je vdy annotation.Annotation

Metody nesm mt dn parametry

Metody nesm mt dn typov parametry
( T getAnnotation(Class annotationType); )

Deklarace metod nesm obsahovat throws

Deklarace vlastnosti 4

Nvratov hodnota mus bt: Primitivn typ

String

Class

Enum

Anotace

Pole pedchozch typ

@interface Illegal { String[][] value(); }

Deklarace pklad 2

public @interface Name { String first(); String last();}public @interface Author { Name value();}

Deklarace pklad 3

public @interface Foo { }

public @interface RequestForEnhancement { int id(); String synopsis(); String engineer() default "[unassigned]"; String date() default "[unimplemented]";}

Pouit pklad 1

@RequestForEnhancement( id = 2868724, synopsis = "Provide time-travel functionality", engineer = "Mr. Peabody", date = "4/1/2004")public void travelThroughTime(Date destination) {

@Preliminary public class TimeTravel {

Pouit gramatika 1

Annotations: Annotation Annotations AnnotationAnnotation: NormalAnnotation MarkerAnnotation SingleElementAnnotation

Pouit gramatika 2

NormalAnnotation: @ TypeName ( ElementValuePairs )ElementValuePairs: ElementValuePair ElementValuePairs , ElementValuePairElementValuePair: Identifier = ElementValue

Pouit gramatika 3

ElementValue: ConditionalExpression Annotation ElementValueArrayInitializerElementValueArrayInitializer: { ElementValues }ElementValues: ElementValue ElementValues , ElementValue

Pouit gramatika 4

MarkerAnnotation: @ TypeNameSingleElementAnnotation: @ TypeName ( ElementValue )

Pouit vlastnosti 1

Mezi @ a identifiktorem me bt mezera

Nesm bt 2 anotace stejnho typu

Mus obsahovat element-value pr pro kad element z pouit anotace (defaultnch ne)

Me bt na libovolnm mst mezi modifiktory (konvence: na prvnm mst)

Pouit vlastnosti 2

Me bt pouita jako modifiktor pro: Package

Class

Interface

lensku promnnou

Metodu

Paramater metody

Konstruktor

Lokln promnnou

Pouit vlastnosti 3

Hodnota nesm bt null

Pokud je element pole a hodnota nen ElementValueArrayInitializer, tak se pouije jako jedin prvek pole

Pouit pklad 2

@Author(@Name(first = "Joe", last = "Hacker"))public class BitTwiddle { ... }

@Quality(Quality.Level.GOOD)public class Karma { ... }

@Copyright("2002 Yoyodyne Systems, Inc., All rights reserved.")public class OscillationOverthruster { ... }

Pouit pklad 3

@RequestForEnhancement( id = 2868724, synopsis = "Provide time-travel functionality" //, // engineer = "Mr. Peabody", // date = "4/1/2004")public void travelThroughTime(Date destination) {

Peddefinovan anotace

Zvisl na pslunm API

Nkter vyaduj speciln smantiku

Anotace, kter potebuj speciln chovn:Target

Retentition

Inherited

Override

SuppressWarnings

Target 1

Specifikuje, k jakmu typu elementu me bt anotace pipojena

Ppustn hodnoty: ANNOTATION_TYPE - deklarace anotace

CONSTRUCTOR - deklarace konstruktoru

FIELD - deklarace lena tdy

LOCAL_VARIABLE - deklarace lokln promnn

PACKAGE - deklarace balku

METHOD - deklarace metody

Target 2

Ppustn hodnoty: PARAMETER - deklarace parametru metody

TYPE - deklarace typu (tda, rozhran, anotace, vtov typ)

@Target(ElementType.TYPE)public @interface Foo { }

Retentition

Specifikuje, kde a jak dlouho bude anotace dostupn

Ppustn hodnoty:SOURCE pouze ve zdrojovm kdu

CLASS v dob kompilace, ignorovna JVM

RUNTIME read-only pro JVM

@Retention(RetentionPolicy.RUNTIME)public @interface Foo { }

Inherited

@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Inherited { }Takto oanotovana anotace se dd

Pouze pro anotace td a interfac

Ukazka: ExInherited

Override

@Retention(RetentionPolicy.SOURCE)@Target(ElementType.METHOD)public @interface Override { }Obas dojde k peten (overload) metedy, ne k jejmu pedefinovn (override)

Ukzka: ExOverride

Override pklad

class A { @Override public boolean equals(A a) { return false; }}Kompiltor: method does not override or implement a method from a supertype

SuppressWarnings

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})@Retention(RetentionPolicy.SOURCE)public @interface SuppressWarnings { String[] value(); }Poskytuje kompiltoru informaci, e m vypnout hlen warning

Uiten pi kompilaci 1.4 kdu 5.0 kompiltorem

SuppressWarnings pklad

@SuppressWarnings("unchecked")public static List toList(Object[] array){return Arrays.asList(array);}

Kompiltor: "List is a raw type. References to generic type List should be parameterized".

Deprecated

@Target(ElementType.RUNTIME)public @interface Deprecated { }

Upozorn na pouit nevhodnho elementu (nebezpen, existuje lep alternativa)

Deprecated pklad

public class Foo { @Deprecated public void myDeprecatedMethod() { ... }}

Kompiltor: "The method myDeprecatedMethod() from the type Foo is deprecated."

Reference

The Java language Specification, Third Edition (http://java.sun.com/docs/books/jls/index.html)

JSR 175: A Metadata Facility for the JavaTM Programming Language (http://www.jcp.org/en/jsr/detail?id=175)

http://www.javabeat.net/articles/java-5-0/2007/08/annotations/

Otzky?

Otzky?

Konec

Dkuji za pozornost!

Muokkaa otsikon tekstimuotoa napsauttamalla

Muokkaa jsennyksen tekstimuotoa napsauttamallaToinen jsennystasoKolmas jsennystasoNeljs jsennystasoViides jsennystasoKuudes jsennystasoSeitsems jsennystasoKahdeksas jsennystasoYhdekss jsennystaso