Java Annotations

29
Annotations in Java Serhii Kartashov April 2013 SoftServe IFDC IT Academy

Transcript of Java Annotations

Page 1: Java Annotations

Annotations in Java

Serhii KartashovApril 2013SoftServeIFDC IT Academy

Page 2: Java Annotations

Agenda

What is Annotations?

Structure of Annotations

Annotations Types

Standard Java Annotations and Categories

Custom Annotations

Process Annotations

Page 3: Java Annotations

Agenda

What is Annotations?

Structure of Annotations

Annotations Types

Standard Java Annotations and Categories

Custom Annotations

Process Annotations

Page 4: Java 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.

Page 5: Java Annotations

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 {

Page 6: Java Annotations

Agenda

What is Annotations?

Structure of Annotations

Annotations Types

Standard Java Annotations and Categories

Custom Annotations

Process Annotations

Page 7: Java Annotations

Structure of AnnotationsEvery 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>;}

Page 8: Java Annotations

Agenda

What is Annotations?

Structure of Annotations

Annotations Types

Standard Java Annotations and Categories

Custom Annotations

Process Annotations

Page 9: Java Annotations

RetentionThis 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:

• ClassWhen the annotation value is given as ‘class’ then this annotation will be compiled and included in the class file.

• RuntimeThe value name itself says, when the retention value is ‘Runtime’ this annotation will be available in JVM at runtime.

• SourceThis annotation will be removed at compile time and will not be available at compiled class.

@Retention(RetentionPolicy.RUNTIME)public @interface MyClass {  String value();}

Page 10: Java Annotations

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 { }

Page 11: Java Annotations

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.

Page 12: Java Annotations

Documented

When a annotation type is annotated with @Documented then wherever this annotation is used those elements should be documented using Javadoc tool

Page 13: Java Annotations

Agenda

What is Annotations?

Structure of Annotations

Annotations Types

Standard Java Annotations and Categories

Custom Annotations

Process Annotations

Page 14: Java 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]"; }

Page 15: Java Annotations

Annotations in Java - @DeprecatedWhen 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();}

}

@Deprecatedprivate static void readingWithObjectOutputStream() throws Exception {

FileInputStream in = new FileInputStream("objectStore.ser");

Page 16: Java Annotations

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

Page 17: Java Annotations

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")

Page 18: Java Annotations

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 {}

Page 19: Java Annotations

Agenda

What is Annotations?

Structure of Annotations

Annotations Types

Standard Java Annotations and Categories

Custom Annotations

Process Annotations

Page 20: Java 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();

}

Page 21: Java Annotations

Custom annotations3. 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) { …}

Page 22: Java Annotations

Agenda

What is Annotations?

Structure of Annotations

Annotations Types

Standard Java Annotations and Categories

Custom Annotations

Process Annotations

Page 23: Java 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();}

Page 24: Java Annotations

Process AnnotationsCreate 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"); }

}

Page 25: Java Annotations

Process AnnotationsLets 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); }}

Page 26: Java Annotations

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; }

Page 27: Java Annotations

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) parameters3. implement simple static assert methods (core your

test framework)4. print result of tests to simple java console.

Page 28: Java Annotations

Questions andAnswers

Page 29: Java Annotations

Useful links

• Links– http://www.ibm.com/developerworks/library/j-annotate1/– http://

www.ibm.com/developerworks/library/j-annotate2/index.html