Annotations in Java Serhii Kartashov April 2013 SoftServe IFDC IT Academy
Agenda What is Annotations? Structure of Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
Agenda What is Annotations? Structure of Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
What is Annotations? • Annotation is code about the code, that is metadata about the program itself. • Organized data about the code, included within the code itself. It can be parsed by the compiler, annotation processing tools and can also be made available at run-time too.
What is Annotations? public class MyClass implements Serializable { private String f1; private transient String f2; } /** * * @author Serhii K. * @version 1.0 * */ public class MyClass implements Serializable {
Agenda What is Annotations? Structure of Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
Structure of Annotations Every annotation belongs to a annotation type. Annotation type is very similar to an interface with little difference: • We attach ‘@’ just before interface keyword. • Methods will not have parameters. • Methods will not have throws clause. • Method return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types. • We can set a default value to method. @Documented, @Inherited, @Retention and @Target are the four available meta annotations that are built-in with Java. @interface <annotation_type_name> { <method_declaration>; }
Agenda What is Annotations? Structure of Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
Retention This meta annotation denotes the level till which this annotation will be carried. When an annotation type is annotated with meta annotation Retention, RetentionPolicy has three possible values: • Class When the annotation value is given as ‘class’ then this annotation will be compiled and included in the class file. • Runtime The value name itself says, when the retention value is ‘Runtime’ this annotation will be available in JVM at runtime. • Source This annotation will be removed at compile time and will not be available at compiled class. @Retention(RetentionPolicy.RUNTIME) public @interface MyClass { String value(); }
Target This meta annotation says that this annotation type is applicable for only the element (ElementType) listed. Possible values for ElementType are, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE. @Target(ElementType.FIELD) public @interface MyClass { }
Inherited This meta annotation denotes that the annotation type can be inherited from super class. When a class is annotated with annotation of type that is annotated with Inherited, then its super class will be queried till a matching annotation is found.
Documented When a annotation type is annotated with @Documented then wherever this annotation is used those elements should be documented using Javadoc tool
Agenda What is Annotations? Structure of Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
Annotations in Java - @Override When we want to override a method, we can use this annotation to say to the compiler we are overriding an existing method. If the compiler finds that there is no matching method found in super class then generates a warning. Though it is not mandatory, it is considered as a best practice. @Override public String toString( ) { return super.toString( ) + " [modified by subclass]"; }
Annotations in Java - @Deprecated When we want to inform the compiler that a method is deprecated we can use this. So, when a method is annotated with @Deprecated and that method is found used in some place, then the compiler generates a warning. … writingWithObjectOutputStream(); readingWithObjectOutputStream(); } catch (Exception e) { e.printStackTrace(); } } @Deprecated private static void readingWithObjectOutputStream() throws Exception { FileInputStream in = new FileInputStream("objectStore.ser");
Annotations in Java - @SuppressWarnings This is like saying, “I know what I am doing, so please shut up!” We want the compiler not to raise any warnings and then we use this annotation. @SuppressWarnings({ "resource", "unused" }) //@SuppressWarnings(value={ "resource", "unused" }) private static void readingWithObjectOutputStream() throws Exception { FileInputStream in = new FileInputStream("objectStore.ser"); //@SuppressWarnings("resource") ObjectInputStream is = new ObjectInputStream(in); //@SuppressWarnings("unused") String note = (String)is.readObject(); MySerialClass serialIn1 = (MySerialClass)is.readObject(); serialIn1.toString(); } @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) @Retention(RetentionPolicy.SOURCE) public @interface SuppressWarnings { String[] value(); } unchecked
Categories of annotations • Marker annotations have no variables. The annotation simply appears, identified by name, with no additional data supplied. For example, @MarkerAnnotation is a marker annotation. It includes no data, just the annotation name. • Single-value annotations are similar to markers, but provide a single piece of data. Because only a single bit of data is supplied, you can use a shortcut syntax (assuming the annotation type is defined to accept this syntax): @SingleValueAnnotation("my data") • Full annotations have multiple data members. As a result, you must use a fuller syntax (and the annotation doesn't look quite so much like a normal Java method anymore): @FullAnnotation(var1="data value 1", var2="data value 2", var3="data value 3")
Custom annotations 1. The @interface declaration Defining a new annotation type is a lot like creating an interface, except that you precede the interface keyword with the @ sign. package org.kartashov; /** * Annotation type to indicate a task still needs to be * completed. */ public @interface TODO { }
Agenda What is Annotations? Structure of Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
Custom annotations 2. Adding a member package org.kartashov; /** * Annotation type to indicate a task still needs to be * completed. */ public @interface TODO { String value(); //String[] value(); }
Custom annotations 3. Setting default values package org.kartashov; public @interface GroupTODO { public enum Severity { CRITICAL, IMPORTANT, TRIVIAL, DOCUMENTATION }; Severity severity() default Severity.IMPORTANT; String item(); String assignedTo(); String dateAssigned(); } @GroupTODO( item="Figure out the amount of interest per month", assignedTo="Brett McLaughlin", dateAssigned="08/04/2004" ) public void calculateInterest(float amount, float rate) { … }
Agenda What is Annotations? Structure of Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
Process Annotations At the first lets create own custom annotation: package org.kartashov.annotations.reflection.developer; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface Developer { String value(); }
Process Annotations Create simple java class with and use our annotations: package org.kartashov.annotations.reflection.developer; public class BuildHouse { @Developer ("Alice") public void aliceMethod() { System.out.println("This method is written by Alice"); } @Developer ("Popeye") public void buildHouse() { System.out.println("This method is written by Popeye"); } }
Process Annotations Lets build GNUMain method: 1. for (Method method : Class.forName( "org.kartashov.annotations.reflection.developer.BuildHouse").getMethods()) { 2. if (method.isAnnotationPresent(Developer.class)) { 3. for (Annotation anno : method.getDeclaredAnnotations()) { 4. Developer a = method.getAnnotation(Developer.class); 5. if ("Popeye".equals(a.value())) { System.out.println("Popeye the sailor man! " + method); } }
Hibernate Example @Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10) public String getStockCode() { return this.stockCode; } public void setStockCode(String stockCode) { this.stockCode = stockCode; }
Home Work Create your own test framework like JUnit. You have to manage follow features: 1. all test methods should be marked with help @Test annotation. 2. this annotations should support “description” and “count” (how many times run this test) parameters 3. implement simple static assert methods (core your test framework) 4. print result of tests to simple java console.
Questions and Answers
Useful links • Links – http://www.ibm.com/developerworks/library/j-annotate1/ – http://www.ibm.com/developerworks/library/j- annotate2/index.html

Java Annotations

  • 1.
    Annotations in Java SerhiiKartashov April 2013 SoftServe IFDC IT Academy
  • 2.
    Agenda What is Annotations? Structureof Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
  • 3.
    Agenda What is Annotations? Structureof Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
  • 4.
    What is Annotations? •Annotation is code about the code, that is metadata about the program itself. • Organized data about the code, included within the code itself. It can be parsed by the compiler, annotation processing tools and can also be made available at run-time too.
  • 5.
    What is Annotations? publicclass MyClass implements Serializable { private String f1; private transient String f2; } /** * * @author Serhii K. * @version 1.0 * */ public class MyClass implements Serializable {
  • 6.
    Agenda What is Annotations? Structureof Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
  • 7.
    Structure of Annotations Everyannotation belongs to a annotation type. Annotation type is very similar to an interface with little difference: • We attach ‘@’ just before interface keyword. • Methods will not have parameters. • Methods will not have throws clause. • Method return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types. • We can set a default value to method. @Documented, @Inherited, @Retention and @Target are the four available meta annotations that are built-in with Java. @interface <annotation_type_name> { <method_declaration>; }
  • 8.
    Agenda What is Annotations? Structureof Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
  • 9.
    Retention This meta annotationdenotes the level till which this annotation will be carried. When an annotation type is annotated with meta annotation Retention, RetentionPolicy has three possible values: • Class When the annotation value is given as ‘class’ then this annotation will be compiled and included in the class file. • Runtime The value name itself says, when the retention value is ‘Runtime’ this annotation will be available in JVM at runtime. • Source This annotation will be removed at compile time and will not be available at compiled class. @Retention(RetentionPolicy.RUNTIME) public @interface MyClass { String value(); }
  • 10.
    Target This meta annotationsays that this annotation type is applicable for only the element (ElementType) listed. Possible values for ElementType are, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE. @Target(ElementType.FIELD) public @interface MyClass { }
  • 11.
    Inherited This meta annotationdenotes that the annotation type can be inherited from super class. When a class is annotated with annotation of type that is annotated with Inherited, then its super class will be queried till a matching annotation is found.
  • 12.
    Documented When a annotationtype is annotated with @Documented then wherever this annotation is used those elements should be documented using Javadoc tool
  • 13.
    Agenda What is Annotations? Structureof Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
  • 14.
    Annotations in Java- @Override When we want to override a method, we can use this annotation to say to the compiler we are overriding an existing method. If the compiler finds that there is no matching method found in super class then generates a warning. Though it is not mandatory, it is considered as a best practice. @Override public String toString( ) { return super.toString( ) + " [modified by subclass]"; }
  • 15.
    Annotations in Java- @Deprecated When we want to inform the compiler that a method is deprecated we can use this. So, when a method is annotated with @Deprecated and that method is found used in some place, then the compiler generates a warning. … writingWithObjectOutputStream(); readingWithObjectOutputStream(); } catch (Exception e) { e.printStackTrace(); } } @Deprecated private static void readingWithObjectOutputStream() throws Exception { FileInputStream in = new FileInputStream("objectStore.ser");
  • 16.
    Annotations in Java- @SuppressWarnings This is like saying, “I know what I am doing, so please shut up!” We want the compiler not to raise any warnings and then we use this annotation. @SuppressWarnings({ "resource", "unused" }) //@SuppressWarnings(value={ "resource", "unused" }) private static void readingWithObjectOutputStream() throws Exception { FileInputStream in = new FileInputStream("objectStore.ser"); //@SuppressWarnings("resource") ObjectInputStream is = new ObjectInputStream(in); //@SuppressWarnings("unused") String note = (String)is.readObject(); MySerialClass serialIn1 = (MySerialClass)is.readObject(); serialIn1.toString(); } @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) @Retention(RetentionPolicy.SOURCE) public @interface SuppressWarnings { String[] value(); } unchecked
  • 17.
    Categories of annotations •Marker annotations have no variables. The annotation simply appears, identified by name, with no additional data supplied. For example, @MarkerAnnotation is a marker annotation. It includes no data, just the annotation name. • Single-value annotations are similar to markers, but provide a single piece of data. Because only a single bit of data is supplied, you can use a shortcut syntax (assuming the annotation type is defined to accept this syntax): @SingleValueAnnotation("my data") • Full annotations have multiple data members. As a result, you must use a fuller syntax (and the annotation doesn't look quite so much like a normal Java method anymore): @FullAnnotation(var1="data value 1", var2="data value 2", var3="data value 3")
  • 18.
    Custom annotations 1. The@interface declaration Defining a new annotation type is a lot like creating an interface, except that you precede the interface keyword with the @ sign. package org.kartashov; /** * Annotation type to indicate a task still needs to be * completed. */ public @interface TODO { }
  • 19.
    Agenda What is Annotations? Structureof Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
  • 20.
    Custom annotations 2. Addinga member package org.kartashov; /** * Annotation type to indicate a task still needs to be * completed. */ public @interface TODO { String value(); //String[] value(); }
  • 21.
    Custom annotations 3. Settingdefault values package org.kartashov; public @interface GroupTODO { public enum Severity { CRITICAL, IMPORTANT, TRIVIAL, DOCUMENTATION }; Severity severity() default Severity.IMPORTANT; String item(); String assignedTo(); String dateAssigned(); } @GroupTODO( item="Figure out the amount of interest per month", assignedTo="Brett McLaughlin", dateAssigned="08/04/2004" ) public void calculateInterest(float amount, float rate) { … }
  • 22.
    Agenda What is Annotations? Structureof Annotations Annotations Types Standard Java Annotations and Categories Custom Annotations Process Annotations
  • 23.
    Process Annotations At thefirst lets create own custom annotation: package org.kartashov.annotations.reflection.developer; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface Developer { String value(); }
  • 24.
    Process Annotations Create simplejava class with and use our annotations: package org.kartashov.annotations.reflection.developer; public class BuildHouse { @Developer ("Alice") public void aliceMethod() { System.out.println("This method is written by Alice"); } @Developer ("Popeye") public void buildHouse() { System.out.println("This method is written by Popeye"); } }
  • 25.
    Process Annotations Lets buildGNUMain method: 1. for (Method method : Class.forName( "org.kartashov.annotations.reflection.developer.BuildHouse").getMethods()) { 2. if (method.isAnnotationPresent(Developer.class)) { 3. for (Annotation anno : method.getDeclaredAnnotations()) { 4. Developer a = method.getAnnotation(Developer.class); 5. if ("Popeye".equals(a.value())) { System.out.println("Popeye the sailor man! " + method); } }
  • 26.
    Hibernate Example @Column(name ="STOCK_CODE", unique = true, nullable = false, length = 10) public String getStockCode() { return this.stockCode; } public void setStockCode(String stockCode) { this.stockCode = stockCode; }
  • 27.
    Home Work Create yourown test framework like JUnit. You have to manage follow features: 1. all test methods should be marked with help @Test annotation. 2. this annotations should support “description” and “count” (how many times run this test) parameters 3. implement simple static assert methods (core your test framework) 4. print result of tests to simple java console.
  • 28.
  • 29.
    Useful links • Links –http://www.ibm.com/developerworks/library/j-annotate1/ – http://www.ibm.com/developerworks/library/j- annotate2/index.html